十、条件渲染

发布时间 2023-12-15 10:09:47作者: 创客未来

if/else 条件渲染

1.支持if、else和else if 语句。

2.if、else if 后跟随的条件语句可以使用状态变量。

3.允许在容器组件内使用,通过条件渲染语句构建不同的子组件。

4.当if、else if 后跟随的状态判断中使用的状态变量值变化时,条件渲染语句会进行更新

5.条件可以包括Typescript表达式

if(表达式){
  组件内容1
}else{
  组件内容2
}

案例代码

/**
 * author:创客未来
 * copyright:com.ckFuture.hrb
 * 分支渲染
 */
@Entry
@Component
struct Branch {
  @State isStudy: boolean = false
  build() {
    Row() {
      Column() {
        Button('toggle').fontSize(50).margin({top:20})
          .onClick(() => {
            this.isStudy = !this.isStudy
          })
        if(this.isStudy){
          Branch_Comp({content:'学习鸿蒙之前-愁容满面'})
        }else {
          Branch_Comp({content:'学习鸿蒙之后-喜上眉梢'})
        }
      }
      .width('100%')
    }
    .height('100%')
  }
}

@Component
struct Branch_Comp{
  content:string
  build() {
    Column() {
      Text(this.content)
        .fontSize(30)
        .margin({top:30})
    }
  }
}

 

ForEach 循环渲染

ForEach接口基于数组类型数据来进行循环渲染,需要与容器组件配合使用,且接口返回的组件盈当是允许包含在ForEach父容器组件中的子组件。例如:ListItem组件要求ForEach的父容器组件必须为List组件。

 

/**
 * author:创客未来
 * copyright:com.ckFuture.hrb
 * 循环渲染
 * todo:重点注意键值生成器返回的数据,保证唯一性。否则会有问题。
 */
@Entry
@Component
struct Loop {
  @State message: string = '循环渲染'
  @State product: string[] = ['PC','问界汽车',"平板",`手环`,'PC']

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Divider()
        ForEach(this.product, (item) => {
          Text(item).fontSize(30)
        }, (item) => {
          //键值生成器
            return item
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

数据的唯一性 

 

/**
 * author:创客未来
 * copyright:com.ckFuture.hrb
 * 循环渲染
 * todo:重点注意键值生成器返回的数据,保证唯一性。否则会有问题。
 */
@Entry
@Component
struct Loop {
  @State message: string = '循环渲染'
  //@State product: string[] = ['PC','问界汽车',"平板",`手环`,'PC']
  @State harmony:object[] =[
    {
      id:'001',
      title:'helloworld',
      content:'入门代码编写'
    },
    {
      id:'002',
      title:'跳转',
      content:'多种语言页面跳转'
    },
    {
      id:'003',
      title:'ArkTS',
      content:'详细学习arkts语法内容'
    },
    {
    id:'004',
    title:'ArkTS',
    content:'详细学习arkts语法内容'
  }
  ]

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Divider()
        ForEach(this.harmony, (item) => {
          Text(`${item.id} - ${item.title}`).fontSize(30)
        }, (item) => {
          //键值生成器
            return item.id
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}