gpt4 book ai didi

javascript - 使用 useRef 和窗口调整大小事件(React Hook)观察 div 元素大小/尺寸

转载 作者:行者123 更新时间:2023-12-05 06:16:31 25 4
gpt4 key购买 nike

我正在尝试使用 React Hook JS 不断观察/检测 div 元素大小。我使用了不同的方法,但每次我看到一个常见问题,即减小窗口大小不会改变 ref.current.offsetWidth 但增加它会改变 ref.current.offsetWidth值。

这是我的代码:

function Chart({}) {
const targetRef = useRef(null);
const [dimensions, setDimensions] = useState({width: 0, height: 0});

const updateDimensions = debounce(() => {
if(targetRef.current) {
setDimensions({
width: targetRef.current.offsetWidth,
height: targetRef.current.offsetHeight
});
}
}, 50);

useEffect(() => {
updateDimensions();
}, []);

useEffect(() => {
window.addEventListener("resize", updateDimensions);
updateDimensions();
return () => {
window.removeEventListener("resize", updateDimensions);
};
}, []);

return (
<div style={{minHeight: 250}} ref={targetRef}>
<some svg component/>
</div>

);
}

注意:重新呈现整个应用会更新尺寸,但我不想刷新整个页面以获得正确的尺寸。

最佳答案

如果您想使用 refs(或什至使用原始元素)测量某些元素的大小,那么我推荐这个库: https://github.com/ZeeCoder/use-resize-observer

如果你想专门测量窗口的大小,那么最好使用这样的东西:https://github.com/jaredLunde/react-hook/tree/master/packages/window-size#readme

关于javascript - 使用 useRef 和窗口调整大小事件(React Hook)观察 div 元素大小/尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62078290/

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