在调整大小后,获得React组件的宽度的最佳实践是什么?
我有一个可重大的按钮,并且需要在调整大小时立即获取宽度:
useEffect(() => {
if (myRef.current) setButtonWidth(myRef.current.offsetWidth);
}, [myRef.current?.offsetWidth]);
这可以根据需要起作用,在每个调整大小之后获得宽度,但我的理解是,将REF放入使用效果的情况下是一种反图案这?
每个调整大小后,要获得组件的宽度是什么最好的做法?
I have a resizable button, and need to get the width as soon as it's been resized:
useEffect(() => {
if (myRef.current) setButtonWidth(myRef.current.offsetWidth);
}, [myRef.current?.offsetWidth]);
This works as it should, getting the width after every resize, but it's my understanding that it's an anti-pattern to put a ref in a useEffect like this?
What would be the best practice to go about getting the width of the component after each resize?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
ref
获得DOM元素的大小是完全可以的。但是,使用a rase size observer 跟踪元素的大小。To get the size of a dom element using a
ref
is completely okay. However, using a Resize Observer would be a more canonical way to track an element's size.