高阶组件(HOC)和窗口调整大小侦听器

时间:2020-01-17 19:20:49

标签: javascript reactjs dom-events event-listener window-resize

我有以下HOC,我考虑过创建3个状态,这些状态将是我的断点

  • 移动
  • 平板电脑
  • 桌面

但是我想知道当达到断点时如何将这些状态设置为true:

  • 移动电话:少于767
  • 平板电脑:在768至991之间
  • 桌面:992年至1919年之间
  • 大屏幕:1919和2520

然后当这些断点之一到达时,状态将变为true

在HOC中,我现在该怎么做才能只传递一个状态(以正确为准)?

我可以改善这种逻辑吗?

import React from "react";

const withWindowResize = Component => {
  class WrappedComponent extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        height: 0,
        width: 0,
        mobile: false,
        desktop: false,
        tablet: false
      };
      window.addEventListener("resize", this.resizeUpdate);
    }

    componentDidMount() {
      this.update();
    }

    resizeUpdate = () => {
      this.setState({
        height: window.innerHeight,
        width: window.innerWidth
      });
    };

    render() {
      return <Component />;
    }
  }
  return WrappedComponent;
};

export default withWindowResize;

1 个答案:

答案 0 :(得分:1)

有很多方法可以执行此操作,但是按照您的方法,您可以执行以下操作,其中根据以上提供的规范,状态更改只有一个size变量。

通过这种方式,您只需要将this.state.size传递给组件。

import React from "react";

const withWindowResize = Component => {
  class WrappedComponent extends React.PureComponent {
    constructor(props) {
      super(props);

      this.state = {
        size: this.findSize()
      };
    }

    componentDidMount() {
      window.addEventListener("resize", this.resizeUpdate.bind(this)); // initialize your listener
    }

    componentWillUnmount() { // remove event listener on component unmount
      window.removeEventListener("resize", this.resizeUpdate.bind(this));
    }

    findSize() {
      return window.innerWidth > 1919
          ? "large"
          : window.innerWidth > 992
          ? "desktop"
          : window.innerWidth > 768
          ? "tablet"
          : "mobile"; // find currentSize
    }

    resizeUpdate() {
      const currentSize = this.findSize();

      this.setState({
        size: currentSize
      });
    }

    render() {
      return <Component size={this.state.size} />;
    }
  }

  return WrappedComponent;
};

export default withWindowResize;

请注意,我使用React.PureComponent作为,我们不想更改状态并在每次调整窗口大小时重新渲染Component

这与使用React.Component并在使用this.setState之前进行检查相同,如果我们的currentSize与我们处于打开状态的状态不同,则在更新它之前。

if (currentSize !== this.state.size) {
  this.setState({
    size: currentSize
  });
}