HarmonyNote.TOP鸿蒙开发笔记

ArkTs中的ForEach和forEach

在ArkTs语言中,有两个容易混淆的关键字ForEach和forEach,它们相同的作用都是遍历集合数据,但是可使用的地方完全不同。

一、ForEach只能存在于UI结构中

ForEach只能存在于UI容器内,比如给Grid容器根据集合数据生成若干个GridItem,示例如下:

@Component
struct xxx{
  build() {
    Grid(){
      ForEach(this.someList, (item: SomeModel)=>{
        GridItem(){
          Image($r(item.img_url))
        }
      })
    }.columnsTemplate('1fr 1fr')
    .columnsGap(2)
    .rowsGap(2)
    .showBorderEdge()
  }
}

二、forEach只能存在于非UI结构代码中

区别于ForEach,forEach只能存在于非UI结构代码中,比如点击事件的逻辑代码之中,示例如下:

@Component
struct xxx{
  @ObjectLink
  someList: SomeModel[]
  build() {
    Column(){
      Grid(){
        ForEach(this.someList, (item: SomeModel)=>{
          GridItem(){
            //some UI
          }.onClick(()=>{
            this.someList.forEach((item: SomeModel, itemIndex: number)=>{
              // some logical code
            })
          })
        })
      }
    }
  }
}