鸿蒙状态管理-@Builder自定义构建函数

@Builder 将重复使用的UI元素抽象成一个方法 在build方法里调用 使其成为 自定义构建函数

复制代码
@Entry
@Component
struct BuilderCase {
  build() {
    Column(){
      Row(){
        Text("西游记")
          .fontSize(20)
      }
      .justifyContent(FlexAlign.Center)
      .backgroundColor("#f3f4f5")
      .height(60)
      .borderRadius(8)

      .width("100%")
      .padding({
        left:20,
        right:20
      })
    }
    .padding(20)
  }
}

将其中项 抽离出来

复制代码
@Entry
@Component
struct BuilderCase {
  @Builder
  getItemBuilder(itemName:string){
    Row(){
      Text(`${itemName}`)
        .fontSize(20)
    }
    .justifyContent(FlexAlign.Center)
    .backgroundColor("#f3f4f5")
    .height(60)
    .borderRadius(8)

    .width("100%")
    .padding({
      left:20,
      right:20
    })
  }

  build() {
    Column({ space:20 }){
      this.getItemBuilder("西游记")
      this.getItemBuilder("水浒传")
      this.getItemBuilder("红楼梦")
      this.getItemBuilder("三国演义")
    }
    .padding(20)
  }
}

同时我们也可以利用循环生成 简化代码

复制代码
 @State
  list:string[]=[ '西游记','水浒传','红楼梦','三国演义', ]


      ForEach(this.list,(item:string)=>{
        this.getItemBuilder(item)
      })
相关推荐
OH_TPC6 小时前
【鸿蒙优选三方库】@ohos/mpchart:让 HarmonyOS 应用的数据可视化开箱即用
华为·信息可视化·harmonyos·鸿蒙
轻口味11 小时前
端侧 AI 赋能鸿蒙版 Obsidian:轻规划基于 HarmonyOS 7.0 图像超分特性的体验突破与开发实战
人工智能·华为·harmonyos·鸿蒙
OH_TPC13 小时前
【鸿蒙优选三方库】@ohos/lottie:让 After Effects 动画在 HarmonyOS 上稳定播放
华为·harmonyos·鸿蒙
2501_9197490315 小时前
华为鸿蒙训练口才APP—小羊口才
华为·harmonyos·鸿蒙
woshihuanglaoshi17 小时前
鸿蒙老旧项目升级改造高级:API废弃迁移/ArkTS语法升级/架构重构策略/增量迁移/风险管控方案
学习·华为·重构·架构·harmonyos·鸿蒙
M-Robots echo2 天前
王成录:分布式软总线是 M-Robots 实现群体智能的技术内核
机器人·ros·鸿蒙·开源社区·m-robots
OH_TPC2 天前
【鸿蒙优选三方库】@ohos/ijkplayer:在鸿蒙上像 B 站一样流畅播视频
华为·音视频·harmonyos·鸿蒙
2501_919749032 天前
华为鸿蒙经期记录APP—小羊月经
华为·harmonyos·鸿蒙
黑鲨吃西瓜2 天前
鸿蒙通用模块
harmonyos·鸿蒙
math_hongfan3 天前
鸿蒙离线数据缓存高级架构:弱网预加载/离线数据优先级/同步冲突解决/上线后数据合并策略
学习·缓存·华为·架构·harmonyos·鸿蒙