条件渲染 if/else

@Entry
@Component
struct ViewA1 {
  @State count: number = 0;

  build() {
    Column() {
      Text(`计数=${this.count}`)

      if (this.count ==5) {
        Text(`数字等于5`)
          .fontColor(Color.Green)
      } else {
        Text(`数字不等于5`)
          .fontColor(Color.Red)
      }

      Button('增加')
        .onClick(() => {
          this.count++;
        })

      Button('减少')
        .onClick(() => {
          this.count--;
        })
    }
  }
}

在这里插入图片描述

如果数字等于5和不等于5,给出提示

if语句嵌套

@Entry
@Component
struct ViewA1 {
  @State count: number = 0;
  // 设置boolean变量,切换颜色
  @State toggleColor: boolean = false;

  build() {
    Column() {
      Text(`计数=${this.count}`)

      if (this.count >5) {
        if(this.toggleColor){
          Text(`数字大于5`).fontColor(Color.Green).backgroundColor('#ff0000')
        }else{
          Text(`数字大于5`).fontColor(Color.Green)
        }

      } else {
        Text(`数字小于等于5`)
          .fontColor(Color.Red)
      }

      Button('增加')
        .onClick(() => {
          this.count++;
        })

      Button('减少')
        .onClick(() => {
          this.count--;
        })

      Button('切换背景颜色')
        .onClick(() => {
          this.toggleColor = !this.toggleColor;
        })
    }
  }
}

在这里插入图片描述

计数大于5时,切换背景颜色

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐