繁体   English   中英

有条件地呈现按钮的内容

[英]Conditionally rendering contents of a button

我正在做一个记忆游戏CodeSandbox ,我正在尝试完成以下任务:

  1. 使最初要发行的卡面朝下(可以说是隐藏图标)
  2. onClick,显示被点击的卡片上的图标,不显示其他图标
  3. 单击第二张卡时,将显示该图标,如果它们匹配,则无论如何都将其删除(该部分有效),但如果不匹配,则图标将再次隐藏。

我尝试在父div中添加“ buttonMask”类,但它覆盖了我现有的类。 我试过显示:父div也没有,也没有运气。

其他尝试包括向Card.js组件this.state.isHidden:true添加state属性,并尝试切换可见性。 我阅读了ThisSOeddyerburgh的文档 我被困在这种情况下渲染,其他一切都很好,这块让我

这是我发卡的条件

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} 
   />;
 }

最初,当我第一次尝试此操作时,我将状态传递给所有卡,而不仅仅是单个卡,这就是为什么我无法单独切换它们的原因。

这是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>
    );
  }

如果使用逻辑&&,则可以有条件地使用内联呈现元素:

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