HarmonyOS 组件变量被@Link修饰,如何使用ForEach批量创建组件

class GreenButtonState {  
  width: number = 0;  
  
  constructor(width: number) {  
    this.width = width;  
  }  
}  
  
@Component  
struct GreenButton {  
  @Link greenButtonState: GreenButtonState;  
  
  build() {  
    Button('Green Button')  
      .width(this.greenButtonState.width)  
      .height(40)  
      .backgroundColor('#64bb5c')  
      .fontColor('#FFFFFF,90%')  
      .onClick(() => {  
        if (this.greenButtonState.width < 700) {  
          // 更新class的属性,变化可以被观察到同步回父组件  
          this.greenButtonState.width += 60;  
        } else {  
          // 更新class,变化可以被观察到同步回父组件  
          this.greenButtonState = new GreenButtonState(180);  
        }  
      })  
  }  
}  
  
@Component  
struct YellowButton {  
  @Link yellowButtonState: number;  
  
  build() {  
    Button('Yellow Button')  
      .width(this.yellowButtonState)  
      .height(40)  
      .backgroundColor('#f7ce00')  
      .fontColor('#FFFFFF,90%')  
      .onClick(() => {  
        // 子组件的简单类型可以同步回父组件  
        this.yellowButtonState += 40.0;  
      })  
  }  
}  
  
@Entry  
@Component  
struct ShufflingContainer {  
  build() {  
    Column() {  
      Swiper(this.swiperController) {  
        ForEach(this.data, (item: GreenButtonState , index: number) => {  
          这里如何批量创建GreenButton 和YellowButton  
        })  
      }  
    }  
  }  
}  
}
  • 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.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
HarmonyOS
2024-09-25 12:26:35
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

在初始化渲染时,foreach会加载数据源的所有数据,并为每个数据创建对应的组件,然后将其挂载到渲染树上,如果数据源非常大或有特定的性能需求,建议使用lazyForEach组件,参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-rendering-control-lazyforeach-0000001820879609-V5#ZH-CN_TOPIC_0000001834460352__idatasource%E7%B1%BB%E5%9E%8B%E8%AF%B4%E6%98%8E

分享
微博
QQ
微信
回复
2024-09-25 18:18:39
相关问题
组件与子组件使用@Link双向同步
2095浏览 • 1回复 待解决
HarmonyOS 如何组件使用临时变量
1251浏览 • 1回复 待解决
HarmonyOS 批量修改子组件的颜色
649浏览 • 1回复 待解决
HarmonyOS @Link使用问题
689浏览 • 1回复 待解决
django怎么解决批量创建用户问题?
5423浏览 • 1回复 待解决
HarmonyOS ui组件内部如何定义变量
692浏览 • 1回复 待解决
组件属性width是否支持使用变量定义
1078浏览 • 1回复 待解决