在调整大小后,获得React组件的宽度的最佳实践是什么?

发布于 2025-02-03 09:24:44 字数 282 浏览 2 评论 0原文

我有一个可重大的按钮,并且需要在调整大小时立即获取宽度:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小忆控 2025-02-10 09:24:44

使用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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文