[英]React - Each child in a list should have a unique “key” prop
In My react component, My UI loads perfectly but there is console error which i wanted to fix error says - ' Each child in a list should have a unique "key" prop
' for below code.在我的反应组件中,我的 UI 加载完美,但有控制台错误,我想修复错误说 - ' Each child in a list should have a unique "key" prop
',用于下面的代码。 Guide me how I can pass keys to detailsContent
指导我如何将密钥传递给detailsContent
render() {
const header = (
<div className={css.deviceDetailsBody}>
<div className="sidebar__header">
<div className="sidebar__title">
<div>
{hostname}
{this._renderCloser()}
<div className={"sidebar__subtitle"}>
<div className="toolsBar">
<div className="toolsBarlet">
<div className="toolsItemNarrow">{deviceTypeView}</div>
{complianceStatusView}
<div className="toolsItemNarrow">{managementIpAddress}</div>
{deviceUpTime}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
const horizontalLine = <div className="sidebar__horiz_line" />;
const body = (
<div className="body">
{tabs}
{tools}
</div>
);
const detailsContent = [header, horizontalLine, body].map(
currentComponent => currentComponent
);
return (
<div>
{sideBarShow && (
<Sidebar {...sidebarProps}>
<div>{detailsContent}</div>
</Sidebar>
)}
</div>
);
}
Added the header, body code for more clarity.添加了 header,正文代码更清晰。
Each child in a list should have a unique "key" prop列表中的每个孩子都应该有一个唯一的“关键”道具
If using Components and not plain jsx elements, simply add a key
prop to the currentComponent
jsx.如果使用组件而不是普通的 jsx 元素,只需将key
prop 添加到currentComponent
jsx。 Note for simplicity I just used index
as key.请注意,为简单起见,我只是使用index
作为键。
const detailsContent = [header, horizontalLine, body].map(
(CurrentComponent, index) => (<CurrentComponent key={index} />)
);
Using elements, please refer to the accepted answer .使用元素,请参考接受的答案。
You can use React.cloneElement
to add keys您可以使用React.cloneElement
添加键
const detailsContent = [header, line, body].map(
(element, index) => React.cloneElement(element, {key: index})
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.