[英]How can I set 2 values for one variable, and the component will render with one value, depending of some prop input
[英]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.