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

标签 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;

最佳答案

有很多方法可以做到这一点,但是按照您的方法,您可以执行如下操作,其中您只需根据上面提供的规范更改状态的 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
  });
}

关于javascript - 高阶组件 (HOC) 和窗口调整大小监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59793649/

相关文章:

reactjs - 如何在不使用 FormattedMessage 的情况下在 ReactIntl​​ 2.0 中检索字符串

Javascript 回调函数和参数

javascript - 如何使用 jquery 删除起始 div 元素?

javascript - 如何避免在每次渲染时执行 useState 函数参数(获取初始值)?

node.js - require(variable) 导致错误 Cannot find module "."

Javascript 事件调用者未被传递到参数中

javascript - 子窗口关闭时如何调用父窗口的JavaScript函数?

javascript - 全屏 vimeo 视频播放后如何重定向 URL?

javascript - Javascript : while or for statements? 什么更有效率

javascript - 为什么在别处点击鼠标会触发onmousedown?