簡體   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