我想限制父容器组件可以容纳的组件数量。
Say I have an item container where I render dozens of Item
components. Container has a height limit of 220px
and each Item
has a height of 50px
(for sake of simplicity of this example - real code would have Item
of different height).
Using React, I want to limit amount of Item
components that container can fit, relative to it's height. Therefore, before placing each Item
into the container, I need to verify, whether container doesn't overflow and if it is, stop render more items into it.
我使用以下代码实现此目的:
const [canRender, setCanRender] = useState(true);
useEffect(() => {
const parent = ref.current.parentElement;
setCanRender(parent.clientHeight <= parent.scrollHeight);
}, []);
在给定的示例中,仅应渲染3个Item组件,因为容器不能容纳更多的组件。 我的问题是React会立即渲染所有组件(由于状态未同步设置?)。
How can I conditionally render Item
component one by one and check for container overflow?