简体   繁体   English

有条件地呈现按钮的内容

[英]Conditionally rendering contents of a button

I am making a memory game, CodeSandbox , and I am trying to accomplish the following: 我正在做一个记忆游戏CodeSandbox ,我正在尝试完成以下任务:

  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 onClick,显示被点击的卡片上的图标,不显示其他图标
  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. 我尝试在父div中添加“ buttonMask”类,但它覆盖了我现有的类。 I tried display: none in the parent div also, no luck. 我试过显示:父div也没有,也没有运气。

Other attempts included adding a state property to the Card.js component this.state.isHidden: true and trying to toggle the visibility. 其他尝试包括向Card.js组件this.state.isHidden:true添加state属性,并尝试切换可见性。 I read the docs, This , SO , and eddyerburgh . 我阅读了ThisSOeddyerburgh的文档 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 这是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>
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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