【发布时间】:2020-04-10 22:37:58
【问题描述】:
我正在 React 中生成 dl:
<dl>
{
highlights.map(highlight => {
const count = text.split(highlight).length - 1;
return (
<>
<dt key={`dt-${highlight.id}`}>{highlight}</dt>
<dd key={`dd-${highlight.id}`}>{count}</dd>
</>
);
})
}
</dl>
这给了我警告:
警告:列表中的每个孩子都应该有一个唯一的“key”属性。
这将删除警告,但不会生成我想要的 HTML:
<dl>
{
highlights.map(highlight => {
const count = text.split(highlight).length - 1;
return (
<div key={highlight.id}>
<dt>{highlight}</dt>
<dd>{count}</dd>
</div>
);
})
}
</dl>
而且我无法将 key 属性添加到片段 (<> </>)。
如何解决这个问题?
我正在使用 React 16.12.0。
【问题讨论】:
-
<React.Fragment key={'foo'}>。不要使用快捷语法。见keyed fragments -
只是一个建议,不要使用索引作为键。在这里查看原因:react using index as key for items in the list
标签: javascript reactjs jsx