ForEach什么情况下会触发复用

List+ForEach在什么情况下子组件会触发复用?

HarmonyOS
2024-06-05 20:46:35
1.2w浏览
收藏 0
回答 2
回答 2
按赞同
/
按时间
hmogy
1

触发复用有两种场景:

1. 一帧内重复创建多个已被销毁的自定义组件。

2. 反复切换条件渲染控制分支,且控制分支中的组件子树结构较重。

示例代码:

@Entry 
@Component 
struct MyComponent { 
  // data: MyDataSource2 = new MyDataSource2(); 
  @State data: DataI[] = [] 
  comType:string[] =['text', 'image', 'row', 'col'] 
 
  aboutToAppear() { 
    this.data = new Array(20).fill(1).map((i: number,idx): DataI => { 
      return { 
        str: idx + '', 
        type: this.comType[idx % this.comType.length] 
      } 
    }) 
  } 
 
  build() { 
    Column(){ 
      Button('update').onClick(()=>{ 
        this.data = new Array(20).fill(1).map((i: number,idx): DataI => { 
          return { 
            str: idx + '_update', 
            type: this.comType[idx % this.comType.length] 
          } 
        }) 
      }).height(60) 
      List() { 
        ForEach(this.data, (item: DataI, index) => { 
          ListItem() { 
            // if(item){ 
            Gizmos({ data: item, Child: ChildComponent }) 
              .reuseId(item.type) 
            // } 
          } 
          .borderColor(Color.Black) 
          .borderWidth(3) 
        }, (item: DataI) => item.str) 
      } 
      .layoutWeight(1) 
      .cachedCount(1) 
    } 
    .width('100%') 
    .height('100%') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
分享
微博
QQ
微信
回复
2024-06-06 21:16:35
在敲键盘的小鱼干很饥饿

上面的回答学到了,l厉害了

分享
微博
QQ
微信
回复
2024-12-17 09:25:16


相关问题
什么情况下会使用多Module
2718浏览 • 1回复 待解决
什么情况下使用?
1063浏览 • 1回复 待解决
HarmonyOS 手机静音情况下,无法震动
579浏览 • 1回复 待解决