React 监听屏幕尺寸变化
1.在componentDidMount()中加入监听器
componentDidMount() { this.screenChange();}
screenChange() { window.addEventListener('resize', this.resize); }
resize()方法中,定义了屏幕尺寸变化后需要执行的代码
2.在constructor中绑定resize()
constructor(props) { this.resize.bind(this);}
3.在componentWillUnmount()中移除监听器
componentWillUnmount() { window.removeEventListener('resize',this.resize);}
注:一定要移除监听器,否则多个组件之间会导致this的指向紊乱!!!
---------------------
作者:wxj的小博客
来源:CSDN
原文:https://blog.csdn.net/qq_41277245/article/details/79984212
版权声明:本文为作者原创文章,转载请附上博文链接!
内容解析By:CSDN,CNBLOG博客文章一键转载插件