鸿蒙 - arkTs:渲染(循环 - ForEach,判断 - if)

ForEach循环渲染:

参数:

  1. 要循环遍历的数组,Array类型
  2. 遍历的回调方法,Function类型
  3. 为每一项生成唯一标识符的方法,有默认生成方法,非必传

使用示例: 

interface Item {
  name: String,
  price: Number
}

@Entry
@Component
struct Index {
   private arr:Array = [
     {name: '华为 Meta 50', price: 6999},
     {name: '华为 Meta 60 pro', price: 7999},
     {name: '华为 Meta X5', price: 12999},
   ];

  build() {
      Column({space: 30}) {
       ForEach(
         this.arr,
         item=>{
           Row(){
             Column() {
               Text(item.name)
                 .fontWeight(FontWeight.Bold)
                 .margin({bottom: 10})
               Text('¥' + item.price)
             }
           }
           .width('100%')
           .backgroundColor("#FFF")
           .padding(20)
         }
       )
      }
      .height('100%')
      .backgroundColor("#999")
    .justifyContent(FlexAlign.Center)
  };
}

效果展示:

鸿蒙 - arkTs:渲染(循环 - ForEach,判断 - if)_第1张图片


if判断渲染:

使用示例:

interface Item {
  name: String,
  price: Number,
  discount?: Number
}

@Entry
@Component
struct Index {
   private arr:Array = [
     {name: '华为 Meta 50', price: 6999, discount: 6666},
     {name: '华为 Meta 60 pro', price: 7999},
     {name: '华为 Meta X5', price: 12999},
   ];

  build() {
      Column({space: 30}) {
       ForEach(
         this.arr,
         item=>{
           Row(){
             Column() {
               if(item.discount){
                 Text(item.name)
                   .fontWeight(FontWeight.Bold)
                   .margin({bottom: 10})
                 Text('原价:¥' + item.price)
                   .fontSize(14)
                   .decoration({ type: TextDecorationType.LineThrough })
                 Text('折扣价:¥' + item.discount)
                   .textAlign(TextAlign.Start)
                 Text('补贴:¥' + (item.price - item.discount))
                   .textAlign(TextAlign.Start)
               }else{
                 Text(item.name)
                   .fontWeight(FontWeight.Bold)
                   .margin({bottom: 10})
                 Text('¥' + item.price)
               }
             }
           }
           .width('100%')
           .backgroundColor("#FFF")
           .padding(20)
         }
       )
      }
      .height('100%')
      .backgroundColor("#999")
    .justifyContent(FlexAlign.Center)
  };
}

效果展示:

鸿蒙 - arkTs:渲染(循环 - ForEach,判断 - if)_第2张图片

你可能感兴趣的:(鸿蒙(arkTs),华为,鸿蒙系统,harmonyos)