ReactJs:如何以最佳方式将条件子级列表传递给父级?

问题描述 投票:0回答:1

我正在尝试创建一个组件,该组件能够接受可变数量的子元素,然后根据状态值有条件地显示每个子元素。让我们从一个简单的组件开始,该组件根据按钮有条件地显示其子组件:

const Parent = () => {
  const [activeChild, setActiveChild] = useState(0);
  
  return (
    <div>
      {
        activeChild === 0 ? <Child1 />
        : activeChild === 1 ? <Child2 />
        : activeChild === 2 ? <Child3 />
        : null
      }
      <button onClick={() => setActiveChild(activeChild + 1)}
    </div>  
  )
}

简单。现在假设我想将其抽象出来,以便可以将其重新用于可变数量的子项:

const App = () => {
  return (
    <>
      <Parent childList={[<Child1 />, <Child2 />, <Child3 />]} />
      <Parent childList={[<Child4 />, <Child5 />]} />
    </>
  )
}

const Parent = ({ childList: React.ReactNode[] }) => {
  const [activeChild, setActiveChild] = useState(0);
  
  return (
    <div>
      {
        childList.map((child, index) => index === activeChild && child)
      }
      <button onClick={() => setActiveChild(activeChild + 1)}
    </div>  
  )
}

我的问题是,如果你通过像上面这样的 props 传入组件,它们在技术上都会渲染吗?如果是这样,处理这种情况的最佳方法是什么?理想情况下,我只希望 2 个应该可见的子级进行渲染,但我担心所有 5 个子级都会渲染。

reactjs optimization children
1个回答
0
投票

此处您应该使用

find
filter
而不是
map

childList.map((child, index) => index === activeChild && child)
© www.soinside.com 2019 - 2024. All rights reserved.