鸿蒙状态管理-@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)
      })
相关推荐
YM52e1 小时前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统
小雨下雨的雨1 小时前
HarmonyOS ArkUI训练营入门-组件掌握系列-Animation 动画效果实现-PC版本
学习·华为·harmonyos·鸿蒙
三声三视4 小时前
Electron 在鸿蒙 PC 上跑 webview,我是怎么把首屏从 4.2s 干到 1.1s 的
华为·electron·harmonyos·鸿蒙
世人万千丶7 小时前
成语接龙小应用 - HarmonyOS ArkUI 开发实战-TextInput与List列表-PC版本
华为·list·harmonyos·鸿蒙·鸿蒙系统
Davina_yu8 小时前
自定义弹窗:使用CustomDialogController实现复杂交互(27)
harmonyos·鸿蒙·鸿蒙系统
世人万千丶9 小时前
家庭记账本小应用 - HarmonyOS ArkUI 开发实战-Tabs与List组件-PC版本
华为·list·harmonyos·鸿蒙
Davina_yu9 小时前
画布Canvas:2D绘图上下文(Context2D)绘制复杂图表(33)
harmonyos·鸿蒙·鸿蒙系统
小雨下雨的雨9 小时前
HarmonyOS ArkUI训练营入门-组件掌握系列-Grid 网格布局深度解析-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统
Davina_yu20 小时前
定时器与任务调度:setTimeout与setInterval的正确使用(19)
harmonyos·鸿蒙·鸿蒙系统
Davina_yu1 天前
数据持久化(2):RelationalStore关系型数据库(SQLite)操作(14)
harmonyos·鸿蒙·鸿蒙系统