【问题标题】:React render specific children反应渲染特定的孩子
【发布时间】:2021-11-11 09:32:46
【问题描述】:

我查看了其他人与此相关的问题,但找不到合适的答案。我想将孩子传递给一个组件,然后在我想要它们的地方拉出特定的孩子,我见过的大多数例子只是让孩子在同一个地方渲染。

我的组件看起来像这样 -

<ParentComponent>

<ChildOne/>
<ChildTwo/>

<ParentComponent/>

当我在父组件中记录 props.children 时,我得到一个包含两个子对象作为对象的数组。有没有一种简单的方法来拉出我需要它的特定孩子,例如{props.children.ChildOne},目前我正在使用props.children[0],这并不理想,因为我们将动态传递孩子 将来,数组长度可能会改变。

非常感谢任何帮助!

【问题讨论】:

  • 这里有很多元素,要检查子元素的类型:stackoverflow.com/questions/27366077/…
  • 显然,你需要使用React.Children和比较child.type === (&lt;ChildOne/&gt;).typechild.type === ChildOne
  • 所有这些似乎都已准备好生产(最小化后工作)。

标签: reactjs children


【解决方案1】:

根据您的具体情况和需求,将子组件作为道具传递可能比使用特殊的children 道具更有意义。然后你可以用任何你喜欢的方式渲染它们。

<ParentComponent childOne={ChildOne} childTwo={ChildTwo} />
...
const ParentComponent = ({ childOne, childTwo }) => {
  return (
    <div>
      {childOne}
      <div>
        {childTwo}
      </div>
    </div>
  );
};

但是,了解您的确切场景将有助于概念化实现这一点的最佳方式。也许你可以重构你的代码以避免像这样传递一个子数组。

【讨论】:

    【解决方案2】:

    其实我说的ReactChildren API 在这里没用。

    你可以这样做:

    import React from 'react';
    import { ChildOne } from './YourFile';
    
    export function ParentComponent({children}) {
      return children.find(child => child.type === ChildOne)
    }
    

    【讨论】:

      【解决方案3】:

      一种方法是通过包含ParentComponent 及其children 的组件中的 state/props/redux 存储管理来控制传递给ParentComponent 的子组件。

      但要根据您的用例获得解决方案,我们可以避免使用 children 道具并在 ParentComponent 上使用我们定义的道具。

      <ParentComponent
          components={[
           {key: 1, component: <div>Hello</div>}
          ]}
      />
      

      所以,我们现在可以从键中过滤。

      查看此demo

      【讨论】:

      • 理想情况下,我们不应该通过读取 React 内部的属性来构建逻辑。
      • OP 似乎不想使用数字来指代其组件。所以我认为key 不是一个好主意。
      猜你喜欢
      • 1970-01-01
      • 2017-04-12
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 2014-12-03
      • 2017-08-28
      相关资源
      最近更新 更多