React JS函数无法捕获浏览器的窗口大小调整

时间:2019-01-16 18:05:49

标签: javascript reactjs

这是我的组件代码。除此“ onResize”功能外,其他所有功能均正常运行。

 class MyComponent extends Component {
      constructor(props) {
        super(props)   
        this.onResize = this.onResize.bind(this)
      }

    onResize = () => {
        window.onresize = () => {
          alert(true)
          //I had tried with 'this.alert(true)' too
        }
      }
    }

    componentDidMount() {
        this.onResize()
      }

    //rest of the code ommited

2 个答案:

答案 0 :(得分:2)

您必须在componentDidMount生命周期中添加事件监听器:

componentDidMount() {
  window.addEventListener('resize', this.handleWindowResize)
}

请记住在卸载组件时删除事件侦听器,以避免内存泄漏:

componentWillUnmount() {
  window.removeEventListener('resize', this.handleWindowResize)
}

答案 1 :(得分:0)

您需要添加事件监听器以调整大小

onResize() {
  this.setState({
    width: $(window).width(), 
    height: $(window).height()
  })
}

componentWillMount() {
    this.onResize();
}

componentDidMount() {
    window.addEventListener("resize", this.onResize);
}

componentWillUnmount() {
    window.removeEventListener("resize", this.onResize);
}