渲染后获得DIV的动态宽度
我想在绘画后获得动态div的宽度,但我无法说出如何绘制。 这就是我正在做的:
const ref=useRef();
useEffect(()=>{
console.log('REF',ref.current.offSetWidth)
},[])
return (
<div ref={ref}>
</div>
我尝试了window。升压eventlistener,但是只有在屏幕尺寸更改时才会触发它。我的问题无论如何在屏幕上呈现DIV的宽度吗?我没有事先设置宽度,它只是将父母元素的100%在flex框中拿到
I want to get the width of a dynamic div after it's painted, but I can't tell how.
This is what I am doing :
const ref=useRef();
useEffect(()=>{
console.log('REF',ref.current.offSetWidth)
},[])
return (
<div ref={ref}>
</div>
I tried window.resize eventListener, but it only gets triggered if the screen dimensions changed. My question is there anyway to get the width of a div after it renders on the screen ? I'm not setting the width beforehand, it's just taking 100% of parent element inside a flex box
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 resizeobserver ,使用React的简单实现可以是这样的事情:
You can use the ResizeObserver, a simple implementation with React could be something like this:
我认为您的代码正在起作用。这是一个简短的打字稿实现,可以显示我的观点:
调整大小之前的按钮单击按钮:
[![Enter映像说明在此处] [1]] [1]
调整大小后单击按钮上的控制台结果:
[![Enter Image描述在此处] [2]] [2]
我猜您看不到更改的原因是您在这里只能运行一次。另请注意,REF对象的更改不会自动触发重新渲染。
[1]: https://i.sstatic.net/ucmz4.png
[2]: https://i.sstatic.net/cwpvmm.png
Your code is working I think. Here is a short Typescript implementation to show my point:
Console result on button click before resizing:
[![enter image description here][1]][1]
Console result on button click after resizing:
[![enter image description here][2]][2]
I guess the reason you never see the changes is that you have a use effect here that only runs once. Also note that changes in the ref object will not automatically trigger a re-render.
[1]: https://i.sstatic.net/uCmz4.png
[2]: https://i.sstatic.net/cWpVM.png