![](/img/trans.png)
[英]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.