在React中如何将key prop添加到作为Object传递的元素中

时间:2016-06-21 14:26:12

标签: reactjs

大约代码看起来像这样(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>

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

问题是如何将key = {1}添加到Child组件中的passedComp。我无法在Parent的render方法(以及some_prop)中执行此操作,因为此时我无法知道应该使用哪个键。我需要在Child组件中添加关键prop - 但是这里传递的Comp已经是一个对象了。

如何修改passComp以获得密钥?

  • 更新:

我有

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

除去了React警告,但额外的跨度打破了我的(反应 - 引导程序)CSS。有更好的解决方案吗?

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:2)

对于偶然发现此事的其他人:

注入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...
}

答案 2 :(得分:1)

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

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