React 初学 - 使用 If/Else 条件进行渲染以及使用 && 获得更简洁的条件- 个人笔记50

MyComponent 的 state 中包含一个布尔值,用于跟踪是否要在 UI 中显示某个元素。按钮切换此值的状态。目前,它每次都呈现相同的 UI。用if/else语句重写render()方法,如果display为true则返回当前标记。否则,返回不带h1元素的标记。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      display: true
    }
    this.toggleDisplay = this.toggleDisplay.bind(this);
  }
  toggleDisplay() {
    this.setState({
      display: !this.state.display
    });
  }
  render() {
    // change code below this line
   if(this.state.display){
    return (
       <div>
         <button onClick={this.toggleDisplay}>Toggle Display</button>
         <h1>Displayed!</h1>
       </div>
    );
   }else{
    return (
       <div>
         <button onClick={this.toggleDisplay}>Toggle Display</button>
     
       </div>
    );
   }

  }
};

在这里插入图片描述
在这里插入图片描述

方式二,使用 && 获得更简洁的条件

如果condition为 true,则返回标记。如果 condition 为 false,操作将在判断condition后立即返回false,并且不返回任何内容。你可以将这些语句直接包含在 JSX 中,并通过在每个条件后面写&&来将多个条件串在一起。这允许你在render()方法中处理更复杂的条件逻辑,而无需重复大量代码。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      display: true
    }
    this.toggleDisplay = this.toggleDisplay.bind(this);
  }
  toggleDisplay() {
    this.setState({
      display: !this.state.display
    });
  }
  render() {
    // change code below this line
    return (
       <div>
         <button onClick={this.toggleDisplay}>Toggle Display</button>
       {this.state.display &&  <h1>Displayed!</h1>}
       </div>
    );
  }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值