繁体   English   中英

如何一个一个渲染组件?

[英]How can I render component one by one?

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

假设我有一个项目容器,我在其中渲染了许多Item组件。 Container 的高度限制为220px ,每个Item的高度为50px (为简单起见,实际代码中的Item高度不同)。

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

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

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

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

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

点击查看模拟示例

如何有条件地逐个渲染Item组件并检查容器溢出?

只需将项目呈现逻辑移至 app.js。

工作演示在这里

App.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;

ps 考虑不要使用 math.random 作为键

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM