[英]ReactJS Array fill with key in JSX element
I'm looking for the shortest approach to generate multiple JSX element. 我正在寻找生成多个JSX元素的最短方法。 For example, if I need to generate 10 <span>
I can easily use Array map function 例如,如果我需要生成10 <span>
我可以轻松使用Array map函数
{[...Array(10)].map((x, i) =>
<span key={i} ></span>
)}
There's nothing wrong with the above approach but I want another shorter version like, 上面的方法没有错,但我想要另一个更短的版本,比如
Array(10).fill(<span></span>);
However, React will shout about not having the unique 'key' props. 然而,React会大声说没有独特的“关键”道具。 does anyone have a clean solution without using the random()? 没有使用随机()有没有人有一个干净的解决方案?
The Array(10).fill(<span></span>);
Array(10).fill(<span></span>);
solution has more problems than just the key: It uses the same span for each entry in the array, which is presumably not what you want. 解决方案存在的问题多于关键问题:它对数组中的每个条目使用相同的范围,这可能不是您想要的。
You can use Array#from
: 您可以使用Array#from
:
Array.from({length:10}, (_, i) => <span key={i}></span>);
// or
Array.from(Array(10), (_, i) => <span key={i}></span>);
It still uses a callback, but you're going to need that no matter what. 它仍然使用回调,但无论如何你都需要它。 It's slightly less verbose, and more efficient (not that it matters in 99.999% of cases), than the spread-and-map. 它比传播和地图略显冗长,效率更高(并非在99.999%的情况下更重要)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.