提问者:小点点

如何逐个渲染组件?


我想限制父容器组件可以容纳的组件数量。

假设我有一个项目容器,在其中我渲染了几十个item组件。容器的高度限制为220px,每个项目的高度为50px(为了本示例的简单性,实际代码的项目的高度不同)。

使用React,我想限制容器可以容纳的Item组件的数量,相对于它的高度。因此,在将每个Item放入容器之前,我需要验证容器是否没有溢出,如果溢出,则停止向其中呈现更多项。

我使用以下代码来实现这一点:

  const [canRender, setCanRender] = useState(true);

  useEffect(() => {
    const parent = ref.current.parentElement;
    setCanRender(parent.clientHeight <= parent.scrollHeight);
  }, []);

在给定的示例中,只应呈现3个项组件,因为容器不能容纳更多的项组件。我的问题是React会立即渲染所有组件(因为状态没有同步设置?)。

单击以查看模拟示例

如何有条件地逐个呈现组件并检查容器溢出?


共1个答案

匿名用户

只需将项目渲染逻辑移动到应用程序。js。

工作演示在这里

应用程序。js(编辑:优化代码)

export default function App() {
  const [count, setCount] = useState([]);
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current.clientHeight >= ref.current.scrollHeight) {
      setCount(item => [...item, <Item key={Math.random()} />]);
    }
  }, [count]);

  return (
    <div ref={ref} className="container">
      {count}
    </div>
  );
}

项目js

const Item = () => {
  return <div className="bar">Bar</div>;
};

export default Item;

考虑不要使用数学。随机键