HarmonyOS 开发基础(九)forEach

HarmonyOS 开发基础(九)forEach

HarmonyOS 开发基础(九)forEach_第1张图片

一、基础使用

HarmonyOS 开发基础(九)forEach_第2张图片

@Entry
@Component
struct Index {
  // 创建一个变量,用来存储图片网络网址
  imageUrl: string = 'https://gw.alicdn.com/imgextra/i2/2201227850912/O1CN01B7gVvP1Ibk6HMiDRz_!!2201227850912.jpg_Q75.jpg_.webp'
  // private:修饰符,不能被外部访问,创建一个变量,存储不同手机型号数据
  private items: Array<Object> = [
    {name: '红米k70', image: this.imageUrl, price: 2499},
    {name: '红米k70', image: this.imageUrl, price: 2499},
    {name: '红米k70', image: this.imageUrl, price: 2499},
    {name: '红米k70', image: this.imageUrl, price: 2499},
    {name: '红米k70', image: this.imageUrl, price: 2499},
    {name: '红米k70', image: this.imageUrl, price: 2499},
  ]
  build() {
    Column({space: 15}) {
      Row() {
        Text('商品列表')
          .fontSize(30)
          .fontWeight(600)
      }
        .width('100%')
        .justifyContent(FlexAlign.Start)


      // ForEach:循环渲染,用来循环渲染页面组件
      ForEach(
        // arr 参数一:遍历循环的数据数组
        this.items,
        // itemGenerator 参数二:页面组件生成函数
        (item) => {
          // 循环渲染的组件
          Row() {
            Column() {
              // 图片路径数据为循序出来的数据的 image 数据
              Image(item.image)
                .width(60)
                .height(90)
                .interpolation(ImageInterpolation.High)
            }
            Column() {
              // 文本名字数据为循序出来的数据的 name 数据
              Text(item.name)
                .fontSize(20)
                .fontWeight(600)
                .margin({bottom: 5})
              // 文本名字数据为循序出来的数据的 price 数据
              Text(`${item.price}`)
                .fontColor('#F36')
            }
              .margin({left: 25})
              .alignItems(HorizontalAlign.Start)
          }
            .width('100%')
            .padding(10)
            .alignItems(VerticalAlign.Top)
            .borderRadius('8')
            .backgroundColor('#ffffff')
        },
        // keyGenerator 参数三:可不填 键生成函数,为数组每一项生成一个唯一标识,组件是否重新渲染的判断标准
        (item, index): string => {
          return item + index
        }
      )
    }
      .width('100%')
      .height('100%')
      .padding(20)
      .backgroundColor('#f0eef0')
  }
}

你可能感兴趣的:(HarmonyOS,HarmonyOS,华为,typescript,鸿蒙,ArkTS,ArkUI)