【问题标题】:In React how to add key prop to element passed as Object在 React 中如何将 key prop 添加到作为 Object 传递的元素
【发布时间】:2016-10-23 03:54:07
【问题描述】:

代码大概是这样的(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} 添加到passedComp。我不能在 Parent 的渲染方法中(与 some_prop 一起)这样做,因为此时我不知道应该是什么键。我需要在 Child 组件中添加 key 道具 - 但这里的 passComp 已经是一个对象。

我怎样才能修改passedComp以拥有一个密钥?

  • 更新:

我有

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

它消除了 React 警告,但额外的跨度破坏了我的(以及 react-bootstrap 的)CSS。有没有更好的解决方案?

【问题讨论】:

    标签: reactjs key


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 是的。谢谢。这行得通——尽管你发给我的链接已经更新,现在可以使用 React.cloneElement 完成,无需附加组件。它比我的解决方案要好 - 这需要混乱的 CSS 来挽救这种情况。出于某种原因,有些人不喜欢克隆元素——(这是我以前没有走这条路的原因之一)——但对我来说它看起来不错。我不知道有些人必须克隆实例化对象的反对意见是什么。不管怎么说,还是要谢谢你;对我来说很好(-:
      • 你能举个例子吗?
      【解决方案3】:

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

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

      【讨论】:

      • 你现在可以使用 作为你的虚拟组件
      猜你喜欢
      • 1970-01-01
      • 2018-04-26
      • 2016-02-11
      • 2021-05-11
      • 2016-04-29
      • 2019-05-02
      • 2022-10-20
      • 2019-06-26
      • 1970-01-01
      相关资源
      最近更新 更多