简体   繁体   中英

Conditionally rendering contents of a button

I am making a memory game, CodeSandbox , and I am trying to accomplish the following:

  1. Get the cards to be dealt initially face down (icon hidden so to speak)
  2. onClick, the icon on the card that is clicked is revealed, none of the others is revealed
  3. When the second card is clicked that icon is revealed, if they match the cards are removed anyway (that part works) but if they don't, the icons are hidden again.

I tried adding a "buttonMask" class in the parent div but it overrides my existing class. I tried display: none in the parent div also, no luck.

Other attempts included adding a state property to the Card.js component this.state.isHidden: true and trying to toggle the visibility. I read the docs, This , SO , and eddyerburgh . I'm stuck on this condition render, everything else works great, this piece got me

This is my conditional for dealing the cards

class Cards extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    const card = (
      <div style={sty}>
        {this.props.cardTypes ? (
          this.props.cardTypes.map((item, index) => {
            return (
              <button style={cardStyle} value={item} key={index}>
                {" "}
                {item}{" "}
              </button>
           );
         })
        ) : (
          <div> No Cards </div>
        )}
      </div>
    );
    return <Card card={card} removeMatches={this.props.removeMatches} 
   />;
 }

Originally, when I first tried this, I was passing state to all the cards, not just individual cards, that was why I was not able to toggle them individually.

This was the original render in Cards.js

if (this.state.hidden) {
    return (
      <button
        key={card + index}
        style={btn}
        onClick={this.revealIcon}
        id={card}
      >
        <div style={btnMask}>{card}</div>
      </button>
    );
  } else {
    return (
      <button
        key={card + index}
        style={btn}
        onClick={this.revealIcon}
        id={card}
      >
        <div>{card}</div>
      </button>
    );
  }

You can conditionally render an element with an inline if with logical &&:

return(
  <div>
    {this.props.shouldRenderTheThing && 
    <span>Conditionally rendered span</span>}
  </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