【问题标题】:In react, how can I determine the width of a container before rendering a child image?在反应中,如何在渲染子图像之前确定容器的宽度?
【发布时间】:2021-03-23 11:35:39
【问题描述】:

我有一个图像,我想在父 div 中绝对定位,但在渲染之前我不知道父 div 的大小。

在 React 中,如何在渲染图像之前获取容器的宽度?

只要可行,任何黑客解决方案都是允许的。

让它响应窗口大小变化的奖励。

【问题讨论】:

标签: reactjs


【解决方案1】:

您可以使用 ref 获取 div 元素,然后在效果中检查其大小。您可能会在此时设置状态,因此在您知道大小后再次渲染。

const Example = () => {
  const [width, setWidth] = useState(null);
  useEffect(() => {
    setWidth(containerRef.current.clientWidth);
  }, []);

  const containerRef = useRef(null);

  return (
    <div ref={containerRef}>
      {width !== null && (
        // render an image, using the width however you need to
      )}
    </div>
  )
}

根据您使用此宽度所做的操作,您可能会看到闪烁,因为它渲染一次没有图像,一次渲染一次。如果是这种情况,您可以通过从useEffect 切换到useLayoutEffect 来消除闪烁。这将使第二次渲染是同步的,因此用户将没有机会看到第一次渲染。

让它响应窗口大小变化的奖励。

您可以像这样收听窗口调整大小:

useEffect(() => {
  const handleResize = () => {
    setWidth(containerRef.current.clientWidth);
  }

  window.addEventListener('resize', handleResize);

  return () => window.removeEventListener('resize', handleResize);
}, []);

【讨论】:

  • 一个额外的问题:如果我的图像在表格中并且单元格调整大小怎么办?有没有一种简单的方法来监听/更新?
猜你喜欢
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 2021-01-01
相关资源
最近更新 更多