gpt4 book ai didi

javascript - react .js : useEffect with window resize event listener not working

转载 作者:行者123 更新时间:2023-12-05 00:28:05 24 4
gpt4 key购买 nike

我正在使用此代码来监听函数组件中的调整大小事件,并在调整窗口大小时重新呈现组件。问题是,任何一个事件监听器都没有打印出来,所以我想我对我在这里如何使用 useEffect 有误解。

  const [dimensions, setDimensions] = React.useState({
width: window.innerWidth,
height: window.innerHeight,
});

useEffect(() => {
const handleResize = () => {
console.log(dimensions.width);
setDimensions({
width: window.innerWidth,
height: window.innerHeight,
});
window.addEventListener("load", handleResize, false);
window.addEventListener("resize", handleResize, false);
};
});

最佳答案

import { useState, useEffect } from "react";
// Usage
function App() {
const size = useWindowSize();
return (
<div>
{size.width}px / {size.height}px
</div>
);
}
// Hook
function useWindowSize() {
// Initialize state with undefined width/height so server and client renders match
// Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
// Add event listener
window.addEventListener("resize", handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Remove event listener on cleanup
return () => window.removeEventListener("resize", handleResize);
}, []); // Empty array ensures that effect is only run on mount
return windowSize;
}
SOURCE

关于javascript - react .js : useEffect with window resize event listener not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62846043/

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