2 回答

TA贡献1859条经验 获得超6个赞
您的组件可以是这样的:
class WindowDimensions extends React.Component {
constructor(props) {
super(props);
this.state = {
innerWidth = window.innerWidth
}
}
handleResize = () => {
this.setState({innerWidth: window.innerWidth);
}
componentDidMount() {
window.addEventListener("resize", this.handleResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
render() {
const innerWidth = {state};
if (window.matchMedia("(orientation: landscape)").matches && innerWidth < 1025) {
return (
<MegaMenuContainer provider={provider} /> // hamburger
);
}
else if (innerWidth > 1025) {
return (
<MegaMenuContainerDesktop provider={provider} />
);
}
return (
<MegaMenuContainer provider={provider} /> //Hamburger
);
}
};
不要忘了取消调整大小监听器的订阅。

TA贡献1775条经验 获得超8个赞
您需要一个事件侦听器来监视窗口中的更改,特别是您要侦听该resize事件。
const handleResize = () => {
// put your logic here
console.log(window.innerWidth)
}
window.addEventListener('resize', handleResize)
调整大小时,这将输出窗口的内部宽度。
添加回答
举报