如何使用JSX将元素重复n次

我正在我的应用程序中使用React / JSX来完成我想要的,Lodash。

我需要根据条件重复元素一定次数,该怎么做?

这是元素:

<span className="busterCards">♦</span>;

我将其分配为:

    let card;
    if (data.hand === '8 or more cards') {
      card = <span className="busterCards">♦</span>;
    }

因此,在这种情况下,我需要将元素重复8次。使用Lodash的程序应该是什么?

Eva阿飞2020/03/19 14:35:59

没有任何外部库的最短方法

const n = 8; // Or something else

[...Array(n)].map((e, i) => <span className="busterCards" key={i}>♦</span>)
Mandy小小2020/03/19 14:35:59

没有lodash或ES6扩展语法的解决方案:

Array.apply(null, { length: 10 }).map((e, i) => (
  <span className="busterCards" key={i}>
  </span>
));
阿飞番长2020/03/19 14:35:59

使用_.timeshttps : //jsfiddle.net/v1baqwxv/

var Cards = React.createClass({
    render() {
        return <div>cards {
          _.times( this.props.count, () => <span>♦</span> )
        }</div>;
    }
});
卡卡西猪猪2020/03/19 14:35:59

您可以这样做(不带破折号):

var numberOfCards = 8; // or more.

if (data.hand >= numberOfCards) {
    var cards = [];

    for (var i = 0; i < numberOfCards; i++) {
        cards[i] = (<span className="busterCards">♦</span>);
    }
}
Tony村村2020/03/19 14:35:59

干得好:

let card = [];
_.times(8, () => {
  card.push(<span className="busterCards">♦</span>);
});

您可能想要向每个span元素添加键,以便React不会抱怨缺少key属性:

let card = [];
_.times(8, (i) => {
  card.push(<span className="busterCards" key={i}>♦</span>);
});

有关的更多信息.times,请参见此处:https : //lodash.com/docs#times