在第一次渲染期间从响应式 React 元素获取宽度?

Get width from responsive React element during first render?

我有一个名为 ResultList 的 React 组件,负责在图库中显示产品。

但是为了在每行中选择正确的产品数量,我需要知道我的组件还剩下多少像素,因为还有一些其他逻辑可以确定是否会出现侧边栏和过滤栏是否连同ResultList。因此,ResultListwidth 是响应式的,它是变化的。

我已经构建了这段代码来获取元素的宽度,但现在它不适用于第一次渲染。而且我不知道这是否可行,因为尚未创建元素并且 ref 尚未分配给任何内容。但是,如果我不知道元素的宽度,我该如何选择在第一次渲染时显示多少产品?

见下方 GIF:

我的 ResultList 会是 Item2

问题

如何在第一次渲染期间获得 Item2 的宽度,如果这不可能,我如何隐藏它直到我知道它的可用宽度是多少?有没有比 window.getComputedStyle 更好的方法来获取响应元素的宽度?

代码沙盒Link:

https://codesandbox.io/s/wizardly-blackburn-f1p7j

完整代码:

import React, { useRef, useState } from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";

const S = {};

S.Container_DIV = styled.div`
  display: flex;
  height: 150px;
`;

S.FlexItem1 = styled.div`
  flex: 0 0 200px;
  background-color: lightblue;
`;

S.FlexItem2 = styled.div`
  flex: 1 1 80%;
  background-color: lightcoral;
`;

S.FlexItem3 = styled.div`
  flex: 0 0 160px;
  background-color: lightgreen;
`;

function App() {
  const itemRef = useRef(null);
  const [boolean, setBoolean] = useState(false);
  return (
    <React.Fragment>
      <S.Container_DIV>
        <S.FlexItem1>Item 1</S.FlexItem1>
        <S.FlexItem2 ref={itemRef}>Item 2</S.FlexItem2>
        <S.FlexItem3>Item 3</S.FlexItem3>
      </S.Container_DIV>
      <div>
        <br />
        Item2 width is:{" "}
        {itemRef.current && window.getComputedStyle(itemRef.current).width}
      </div>
      <div>
        <button onClick={() => setBoolean(prevState => !prevState)}>
          Force Update
        </button>
      </div>
    </React.Fragment>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

要等到元素已呈现并因此 ref 具有值,您需要使用效果。 useEffect 有点效果,但在重新计算之前你会看到它渲染一次的闪烁。相反,这是可以使用 useLayoutEffect 的情况。它会渲染一次,然后你进行测量并设置状态,然后它会同步再次渲染,所以不会看到闪烁。

function App() {
  const itemRef = useRef(null);
  const [itemWidth, setItemWidth] = useState(-1);
  const [boolean, setBoolean] = useState(false);
  useLayoutEffect(() => {
   // I don't think it can be null at this point, but better safe than sorry
    if (itemRef.current) {
       setItemWidth(window.getComputedStyle(itemRef.current).width);
    }
  });
  return (
    <React.Fragment>
      <S.Container_DIV>
        <S.FlexItem1>Item 1</S.FlexItem1>
        <S.FlexItem2 ref={itemRef}>Item 2</S.FlexItem2>
        <S.FlexItem3>Item 3</S.FlexItem3>
      </S.Container_DIV>
      <div>
        <br />
        Item2 width is: {itemWidth}
      </div>
      <div>
        <button onClick={() => setBoolean(prevState => !prevState)}>
          Force Update
        </button>
      </div>
    </React.Fragment>
  );
}