【问题标题】:Array of children passed as prop in react在反应中作为道具传递的孩子数组
【发布时间】:2017-04-26 03:12:36
【问题描述】:

当一个子数组作为 prop 传递并循环渲染到父组件中时,react 会抱怨数组迭代时缺少唯一键标识符。

克服警告的正确方法是什么?

我可以在道具下与孩子一起传递钥匙吗?

如果我想在父级渲染时为子级设置密钥,则抱怨子级的 key prop 是只读的。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    如果你分享一些代码会更容易。

    您不应该需要迭代子级来渲染,除非您以某种方式扩充它们。

    class MyComponent extends React.Component {
      render() {
        return (
          <div>
            {this.props.children}
          </div>
        )
      }
    }
    

    如果必须,您可以将它们包装在 div 中并应用密钥代替吗?

    class MyComponent extends React.Component {
      render() {
        return (
          <div>
            {this.props.children.map((child, index) => (<div key={index}>{child}</div>))}
          </div>
        )
      }
    }
    

    我还没有尝试过,但您也许可以克隆元素并更改密钥

    class MyComponent extends React.Component {
      render() {
        return (
          <div>
            {this.props.children.map((child, index) => {React.cloneElement(child, {key: index})})}
          </div>
        )
      }
    }
    

    【讨论】:

    • 我现在有了第一个解决方案,并且 key 包含在 prop 本身中。出于某种原因,这对我来说感觉不对。例如:1,
    • 2
    • ,
    • 3
    • > ]} />
  • 既然可以嵌套它们,为什么还要将它们作为道具传递呢?即&lt;Component&gt;&lt;li&gt;1&lt;/li&gt;&lt;li&gt;2&lt;/li&gt;&lt;li&gt;3&lt;/li&gt;&lt;/Component&gt;(假设Component创建&lt;ul&gt;标签)。
  • 在这种情况下,我不能以这种方式嵌套孩子。它们将作为数组传递给父级,然后父级相应地显示它们。
  • 如果您需要更好的帮助,您需要使用更多代码编辑您的问题。显示父组件和使用它的组件。
  • 但简短的回答是,如果您要呈现一个列表,you must provide the keys when creating the elements。在渲染之前,您也许可以通过cloning the elements 绕过它。
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签