reactjs - React 16 中的事件监听器和引用
问题描述
我有一个元素,我想在渲染元素和调整父级大小时将其宽度设置为等于父级。我正在使用新的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
我怎样才能解决这个问题?
解决方案
您需要使用窗口resize
事件。当您分配事件侦听器时,您需要绑定到构造函数内的正确范围this.updateWidth = this.updateWidth.bind(this);
这也应该去抖动。
试试这个:
class FooterBase extends Component {
constructor(props) {
super(props);
this.footerRef = React.createRef();
this.updateWidth = this.updateWidth.bind(this);
this.state = { width: 0 };
}
updateWidth() {
const width = this.footerRef.current.parentNode.clientWidth;
this.setState({ width });
}
componentDidMount() {
this.updateWidth();
window.addEventListener('resize', this.updateWidth);
}
componentWillUnmount() {
window.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"
></footer>
);
}
}
推荐阅读
- sql - 如何在选择 oracle 中将值分组到单行
- server - 为什么我的 magento 网站占用大量内存?
- python - 类中的 Python 对象实例化(奇怪的行为)
- python - snakemake 使用不同的 shell/conda 环境?
- adobe - 未由 Acrobat Distiller 转换但由 GhostScript 转换的 PostScript 文件
- c# - 有没有一种简单的方法可以为我的 slack 机器人添加用户角色(我正在使用 Bot framework 4 c#)或者我应该自己做
- javascript - 在制作 QR 码之前,如何最好地压缩 JWT?
- .net - 如何在同一应用程序中同时为 Microsoft 帐户和 ADFS 使用身份验证处理程序?
- javascript - 在 nodejs 和 vuejs 的文件夹中获取我保存的图像名称时出错
- powershell - 当“用户已经是组的成员”时结束脚本