我有一个 const
定义了多个与问题无关的函数,所以我只包含一个相关的经过清理的段。让我知道我是否应该包含更多内容。
return (
<React.Fragment key={index}>
<hr className={hrClasses} />
<span className={spanClasses}>
{isTrue ? 'x' : index + 1}
</span>
</React.Fragment>
);
})}
</div>
);
在浏览器中,我看到警告:
Warning: Each child in a list should have a unique "key" prop.
由于 hr
元素不需要唯一的键属性,我该如何解决这个错误?
我尝试了不同的键变体,例如将 key={index}
添加到 hr
元素并重新标记 index
作为 span
的 id
键。我不确定还能尝试什么。任何指导将不胜感激!
最佳答案
您没有将 key 应用于父片段。
You can use <> the same way you’d use any other element except that it doesn’t support keys or attributes. ~ https://reactjs.org/docs/fragments.html#short-syntax
您正在使用 <> 的短语法,它不支持键。使用:
<React.Fragment key={index}>
<hr className={styles.hr} />
<span className={styles.span}>
{isValidated ? 'x' : index + 1}
</span>
<React.Fragment/>
关于html - 列表中的每个 child 都应该有一个唯一的 "key" Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55437234/