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

2023-12-20 16:45:56

ForEach循环渲染:

参数:

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

使用示例:?

interface Item {
  name: String,
  price: Number
}

@Entry
@Component
struct Index {
   private arr:Array<Item> = [
     {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)
  };
}

效果展示:


if判断渲染:

使用示例:

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

@Entry
@Component
struct Index {
   private arr:Array<Item> = [
     {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)
  };
}

效果展示:

文章来源:https://blog.csdn.net/weixin_45536484/article/details/135110012
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。