How to detect if screen size has changed to mobile in React?

前端 未结 5 1576
南方客
南方客 2021-01-30 17:25

I am developing a web app with React and need to detect when the screen size has entered the mobile break-point in order to change the state. Specifically I need my sidenav to b

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 18:04

    This is the same as @Ben Cohen answer but after attaching your function to eventListner, also remove it on componentWillUnmount

    constructor() {
      super();
      this.state = { screenWidth: null };
      this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
    }
    
    componentDidMount() {
        window.addEventListener("resize", this.updateWindowDimensions());
    }
    
    componentWillUnmount() {
        window.removeEventListener("resize", this.updateWindowDimensions)
    }
    
    updateWindowDimensions() {
       this.setState({ screenWidth: window.innerWidth });
    }
    

提交回复
热议问题