在 React 中如何将关键道具添加到作为对象传递的元素

In React how to add key prop to element passed as Object

代码大概是这样的(CoffeeScript)

//In Parent component

render: () ->

  mycomp = <SomeComponent some_prop="something" />

  <ChildComponent passedComp = mycomp />


//In Child component

render: () ->

 someContent = [passedComp, <AnotherComp key={2} />]


 <div>
   {someContent}
 </div>

这会生成有关子组件数组中缺少键的警告。

问题是如何在子组件的passedComp中添加key={1}。我不能在 Parent 的 render 方法中执行此操作(与 some_prop 一起),因为此时我不知道应该使用什么键。我需要在 Child 组件中添加 key 道具 - 但这里 passedComp 已经是一个对象。

如何修改 passedComp 使其拥有密钥?

我有

someContent = [<span key={1}>{passedComp}</span>, <AnotherComp key={2} />]

这消除了 React 警告,但额外的跨度打破了我的(很好的反应-bootstrap)CSS。有更好的解决方案吗?

如果您的组件已经实例化,唯一的方法是 clone your component 并添加 key 属性

对于偶然发现此问题的任何其他人:

另一种注入密钥的潜在方法是添加一个虚拟父代,如下所示:

使用 ES6 语法:

class KeyedComponent extends Component {
  render() {
    // NOTE: This implementation assumes that your dummy component has
    // a single child.
    const child = React.Children.only(this.props.children);
    return child;
  }
}

// Use as follows:

// Stuff before...

render() {
  const someContent = [
    <KeyedComponent key="1">{passedComp}</KeyedComponent>,
    <AnotherComp key="2" />,
  ];
  // Stuff after...
}

您可以使用 React.Fragment 添加密钥而不破坏 CSS 并且无需克隆:

someContent = [<React.Fragment key={1}>{passedComp}</React.Fragment>, <AnotherComp key={2} />]