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
keyattribute toReact.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
keyprop is reserved for React’s internal use and isn’t passed down to child components, so passing it as part of the props tothis.props.childrenwas 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
相关产品推荐
相关产品推荐

