英文:
React keys for static array
问题
const renderedText = () => {
return text.map((e, index) =>
<>
<span key={"t" + index.toString()} className={"text-" + e.player}>{e.text} </span>
<span key={"s" + index.toString()} className={"snippet-" + e.player}>{e.snippet} </span>
</>
)
}
英文:
Inside a React component I need to transform an array of objects into a specific HTML markup, using objects values as class names and building a couple of span
tags, like this:
const renderedText = () => {
return text.map(e =>
<>
<span className={"text-"+e.player}>{e.text} </span>
<span className={"snippet-"+e.player}>{e.snippet} </span>
</>
)}
/// Returning this from the component
<div>{renderedText()}</div>
The result is exactly what I need, but how can I avoid the "unique key prop" warning? The HTML elements I'd like to render are completely static, they are never moved nor deleted. I'm just trying to build a long string of span
items.
I tried this, which seems completely over the top and doesn't even get rid of the warning:
const renderedText = () => {
return text.map((e, index) =>
<>
<span key={"t" + index.toString()} className={"text-"+e.player}>{e.text} </span>
<span key={"s" + index.toString()} className={"snippet-"+e.player}>{e.snippet} </span>
</>
)}
答案1
得分: 3
将密钥添加到片段中。
英文:
Add the key to the fragment instead.
...
<React.Fragment key={key}>
...
</React.Fragment>
Reference:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论