gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:03:33 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com