我有一个元素,我想在渲染元素和调整父元素大小时将其宽度设置为与父元素相等。我正在使用新的React.createRef
API 来实现这一点,目前有以下内容:
class Footer extends Component {
constructor(props) {
super(props);
this.footerRef = React.createRef();
this.state = { width: 0 };
}
updateWidth() {
const width = this.footerRef.current.parentNode.clientWidth;
this.setState({ width });
}
componentDidMount() {
this.updateWidth();
this.footerRef.current.addEventListener("resize", this.updateWidth);
}
componentWillUnmount() {
this.footerRef.current.removeEventListener("resize", this.updateWidth);
}
render() {
const { light, setEqualToParentWidth, className, ...props } = this.props;
const style = setEqualToParentWidth
? { ...props.style, width: this.state.width }
: { ...props.style };
return (
<footer
{...props}
ref={this.footerRef}
style={style}
data-ut="footer"
/>
);
}
}
这似乎编译没有任何错误,并且在安装时准确地调整了自己的大小。然而,一旦它被安装,改变视口宽度并不会改变页脚的宽度。我是否错误地附加了事件侦听器?
我最初也尝试将事件侦听器附加到window
,但这导致我尝试调整屏幕大小TypeError: Cannot read property 'current' of undefined
的第一行updateWidth
。
我怎样才能解决这个问题?