You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React:数组渲染子组件设置key仍触发警告的问题排查

Fixing the "Unique 'key' Prop" Warning with React.Fragment

The core issue here is that you’re passing the key as a regular prop to the child component returned by this.props.children, but React expects the key to be attached directly to the root element of each item in your map—which in this case is the React.Fragment itself.

Keys are a special React attribute used to track individual elements in a list, and they need to live on the element being iterated over (the Fragment here), not get passed down as a child prop.

Corrected Code

<div ref={c => (this._gallery = c)}>
  {thumbs.map((image, index) => {
    return (
      <React.Fragment key={image.key || image.src}>
        {this.props.children({ 
          margin: margin, 
          index: index, 
          image: image, 
          onClick: onClick ? this.handleClick : null 
        })}
      </React.Fragment>
    );
  })}
</div>

Why This Works

  • By moving the key attribute to React.Fragment, you’re giving React a unique identifier for each item in the mapped list, which resolves the warning.
  • Note that you can’t use the shorthand <>...</> fragment syntax when you need to add a key—you must use the explicit <React.Fragment> component instead.
  • The key prop is reserved for React’s internal use and isn’t passed down to child components, so passing it as part of the props to this.props.children was never going to fix the issue.

This change eliminates the warning without adding extra DOM nodes, which is exactly the benefit you wanted from using a Fragment.

内容的提问来源于stack exchange,提问作者neptunian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:39:10