Javascript 如何使用 JSX 重复元素 n 次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34189370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to repeat an element n times using JSX
提问by StillDead
I am using React/JSX in my app in order to accomplish what I want, also, Lodash.
我在我的应用程序中使用 React/JSX 来完成我想要的,还有 Lodash。
I need to repeat an element a certain amount of times depending on a condition. How should I do that?
我需要根据条件重复某个元素一定次数。我该怎么做?
Here is the element:
这是元素:
<span className="busterCards">?</span>;
And I am assigning it like this:
我是这样分配的:
let card;
if (data.hand === '8 or more cards') {
card = <span className='busterCards'>?</span>;
}
So in this case, I need to repeat the element 8
times. What should be the process using Lodash?
所以在这种情况下,我需要重复元素8
时间。使用Lodash的过程应该是怎样的?
采纳答案by Long Nguyen
Here you go:
干得好:
let card = [];
_.times(8, () => {
card.push(<span className="busterCards">?</span>);
});
You may want to add key to each span
element so React won't complain about missing the key attribute:
你可能想为每个span
元素添加 key,这样 React 就不会抱怨缺少 key 属性:
let card = [];
_.times(8, (i) => {
card.push(<span className="busterCards" key={i}>?</span>);
});
For more info about .times
, refer here: https://lodash.com/docs#times
有关 的更多信息.times
,请参阅此处:https: //lodash.com/docs#times
回答by Waiski
The shortest way to do this without any external libraries:
在没有任何外部库的情况下执行此操作的最短方法:
const n = 8; // Or something else
[...Array(n)].map((e, i) => <span className="busterCards" key={i}>?</span>)
回答by Jian Weihang
solution without lodash or ES6 spread syntax:
没有 lodash 或 ES6 扩展语法的解决方案:
Array.apply(null, { length: 10 }).map((e, i) => (
<span className="busterCards" key={i}>
?
</span>
));
回答by pawel
Using _.times
: https://jsfiddle.net/v1baqwxv/
使用_.times
:https: //jsfiddle.net/v1baqwxv/
var Cards = React.createClass({
render() {
return <div>cards {
_.times( this.props.count, () => <span>?</span> )
}</div>;
}
});
回答by Allan
You could do it like this (without lodash):
你可以这样做(没有lodash):
var numberOfCards = 8; // or more.
if (data.hand >= numberOfCards) {
var cards = [];
for (var i = 0; i < numberOfCards; i++) {
cards[i] = (<span className="busterCards">?</span>);
}
}