首页 > 编程笔记 > 通用技能 阅读:2

ArkTS if else条件渲染的用法(附带示例)

ArkTS 提供了渲染控制的能力。条件渲染可根据应用的不同状态,使用 if、else 和 else if 渲染对应状态下的 UI 内容。

if/else 条件渲染使用规则如下:
以下是一个嵌套 if 语句的使用示例:
@Entry
@Component
struct CompA {
  @State toggle: boolean = false;
  @State toggleColor: boolean = false;

  build() {
    Column({ space: 20 }) {
      Text('Before')
        .fontSize(15)

      if (this.toggle) {
        Text('Top True, positive 1 top')
          .backgroundColor('#aaffaa')
          .fontSize(20)

        // 内部 if 语句
        if (this.toggleColor) {
          Text('Top True, Nested True, positive COLOR Nested ')
            .backgroundColor('#00aaaa')
            .fontSize(15)
        } else {
          Text('Top True, Nested False, Negative COLOR Nested ')
            .backgroundColor('#aaaaff')
            .fontSize(15)
        }
      } else {
        Text('Top false, negative top level')
          .fontSize(20)
          .backgroundColor('#ffaaaa')

        if (this.toggleColor) {
          Text('positive COLOR Nested ')
            .backgroundColor('#00aaaa')
            .fontSize(15)
        } else {
          Text('Negative COLOR Nested ')
            .backgroundColor('#aaaaff')
            .fontSize(15)
        }
      }

      Text('After')
        .fontSize(15)

      Button('Toggle Outer')
        .onClick(() => {
          this.toggle = !this.toggle;
        })

      Button('Toggle Inner')
        .onClick(() => {
          this.toggleColor = !this.toggleColor;
        })
    }
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }
}

相关文章