高阶组件 (HOC) 和 window 调整监听器大小

Higher Order Component (HOC) and window resize listener

我有以下 HOC,我想创建 3 个状态,这些状态将作为我的断点

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

然后当达到这些断点之一时,状态将更改为 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;

有很多方法可以做到这一点,但按照您的方法,您可以执行如下操作,其中您只有一个 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,因为 我们不想在每次 window 调整大小时更改我们的状态并重新渲染我们的 Component

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

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