React静态数组的键

huangapple go评论67阅读模式
英文:

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 = () =&gt; {
  return text.map(e =&gt;
    &lt;&gt;
      &lt;span className={&quot;text-&quot;+e.player}&gt;{e.text} &lt;/span&gt;
      &lt;span className={&quot;snippet-&quot;+e.player}&gt;{e.snippet} &lt;/span&gt;
    &lt;/&gt;
)}

/// Returning this from the component
&lt;div&gt;{renderedText()}&lt;/div&gt;

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 = () =&gt; {
  return text.map((e, index) =&gt;
    &lt;&gt;
      &lt;span key={&quot;t&quot; + index.toString()} className={&quot;text-&quot;+e.player}&gt;{e.text} &lt;/span&gt;
      &lt;span key={&quot;s&quot; + index.toString()} className={&quot;snippet-&quot;+e.player}&gt;{e.snippet} &lt;/span&gt;
    &lt;/&gt;
  )}

答案1

得分: 3

将密钥添加到片段中。

英文:

Add the key to the fragment instead.

...
  &lt;React.Fragment key={key}&gt;
    ...
  &lt;/React.Fragment&gt;

Reference:

  1. https://react.dev/reference/react/Fragment#rendering-a-list-of-fragments

huangapple
  • 本文由 发表于 2023年5月18日 04:30:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275980.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定