鸿蒙开发-循环/条件渲染

421 阅读1分钟

一. 循环渲染 ForEach

使用ForEach进行列表循环, 接收三个参数, 参数一为需要遍历的数组, 参数二为一个回调函数 接收(item, index)为参数, 第三个参数为返回唯一key值的函数

image.png

二. 条件渲染

使用 if() { } else { } image.png

商品列表案例:

class CommodityItem {
  name: string
  image: ResourceStr
  price: number
  discount: number // 优惠
  constructor(name: string, image: ResourceStr, price: number, discount: number = 0) {
    this.name = name
    this.image = image
    this.price = price
    this.discount = discount
  }
}

@Entry
@Component
struct Foreach {
  @State list: CommodityItem[] = [
    new CommodityItem('华为mate60', $r('app.media.phone'), 5999),
    new CommodityItem('小米13 Pro', $r('app.media.phone'), 4999, 600),
    new CommodityItem('iphone 15', $r('app.media.phone'), 6999),
    new CommodityItem('华为p60', $r('app.media.phone'), 5999),
    new CommodityItem('vivo x100', $r('app.media.phone'), 5999),
    new CommodityItem('小米13U', $r('app.media.phone'), 5999)
  ]

  build() {
    Column({ space: 15 }) {
      Row() {
        Text('商品列表')
          .fontSize(20)
      }
      .width('100%')
      .backgroundColor('#ccc')
      .padding({top: 20, bottom: 20})
      .justifyContent(FlexAlign.Center)
      Column({ space: 10 }) {
        ForEach(
          this.list,  //数据
          (item: CommodityItem) => {
            Row() {
              Image(item.image)
                .width(100)
              Column({space: 5}){
                Text(item.name)
                  .fontSize(20)
                  .fontWeight(FontWeight.Bold)
                if(item.discount) {
                  Text('原价¥' + item.price)
                    .fontSize(14)
                    .fontColor('#ccc')
                    .decoration({type: TextDecorationType.LineThrough})
                  Text('折扣价¥' + (item.price - item.discount))
                    .fontSize(16)
                    .fontColor('#f90')
                  Text('优惠¥' + item.discount)
                    .fontSize(16)
                    .fontColor('#f90')
                } else {
                  Text('¥' + item.price)
                    .fontSize(16)
                    .fontColor('#f90')
                }
              }
              .justifyContent(FlexAlign.Start)
              .alignItems(HorizontalAlign.Start)
              .margin({left: 10})
            }
            .width('90%')
            .alignItems(VerticalAlign.Top)
          },
          (item: CommodityItem) => item.name
        )
      }

    }
    .alignItems(HorizontalAlign.Center)
  }
}

image.png