ForEach什么情况下会触发复用

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

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

触发复用有两种场景:

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%') 
  } 
}
分享
微博
QQ
微信
回复
2024-06-06 21:16:35
相关问题
什么情况下会使用多Module
935浏览 • 1回复 待解决
如何在多设备情况下使用hdc
260浏览 • 1回复 待解决
candidate 会在哪三种情况下退出?
2342浏览 • 1回复 待解决