简体   繁体   中英

how to make a react component state change on window resize?

I have a sidebar with a canvas animation which is created based on the size of the window.

componentDidMount() {
    let styles = window.getComputedStyle(this.sidebar.current)
    let w = styles.width
    let h = styles.height
    console.log("getComputedStyle:", styles.height, styles.width)
    this.setState({ "isOn": true, "height": h, "width": w })
}

My question is how could the state change according to window size change? I am trying to add a window.onresize function, but I don't know how to pass the component and states.

So, something like this?

You can create a function to handle the resize, and then hook that function to the resize event, also grabbing the height and width from window .

Also, don't forget to clean up the event if the component will be unmounted.

 componentDidMount() { let styles = window.getComputedStyle(this.sidebar.current) let w = styles.width let h = styles.height console.log("getComputedStyle:", styles.height, styles.width) this.setState({ "isOn": true, "height": h, "width": w }) let resizeHandler = () => { this.setState({ "isOn": this.state.isOn, "height": window.innerHeight, "width": window.innerWidth }); } window.addEventListener('resize', resizeHandler); } componentWillUnmount() { window.removeEventListener('resize', resizeHandler); }

If you meant to calculate the navbar width and height when the screen resizes then the better option is to use getBoundingClientRect instead of getComputedStyle .

Following would also work

  onWindowResize = () => {
    const { current: navElement } = this.sidebar;
    if (navElement) {
      let rect = navElement.getBoundingClientRect();
      this.setState({
        height: rect.width,
        width: rect.height
      });
    }
  };

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

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

Code Sandbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM