问题
I am using React/JSX in my app in order to accomplish what I want, also, 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?
回答1:
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:
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
回答2:
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>)
回答3:
solution without lodash or ES6 spread syntax:
Array.apply(null, { length: 10 }).map((e, i) => (
<span className="busterCards" key={i}>
♦
</span>
));
回答4:
Using _.times
: https://jsfiddle.net/v1baqwxv/
var Cards = React.createClass({
render() {
return <div>cards {
_.times( this.props.count, () => <span>♦</span> )
}</div>;
}
});
回答5:
You could do it like this (without 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>);
}
}
来源:https://stackoverflow.com/questions/34189370/how-to-repeat-an-element-n-times-using-jsx