简体   繁体   中英

How to apply rules to only certain elements in array

I have this loop in react:

<div>
   {this.state.dealersDeck.map(function(card, index){
      return <div className="cardFormatDH" key={ index }> {card.rankKey}{card.suit} </div>;
   }, this)}
</div>

This goes through an array of objects and then renders them on screen. This is all good except I would like to format it so I only display the contents at certain points. ie I'm creating blackjack and I don't want the dealers second card to be visible until the end.

I may have to show more code but was wondering if map had some sort of attribute that I could use.

You could add a boolean prop to each card and render based on that:

<div>
   {this.state.dealersDeck.map(function(card, index){
      return { card.display &&
          <div className="cardFormatDH" key={ index }>{card.rankKey} {card.suit} </div> 
      }
   }, this)}
</div>

You can use basic If...Else statements inside map function as well. Moreover you can write more business logic also to add more functionality.

var cardsHTML = this.state.dealersDeck.map(function(card, index){

    if(condition...1){
        return <div className="cardFormatDH" key={ index }> {card.rankKey}{card.suit} </div>
    }

    if(condition...2){
        return <div></div>
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM