鸿蒙状态管理-@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)
      })
相关推荐
萌虎不虎6 小时前
【鸿蒙在 ETS (Extendable TypeScript) 中创建多级目录或文件,可以使用鸿蒙的文件系统 API】
鸿蒙
颜颜yan_6 小时前
【HarmonyOS5】UIAbility组件生命周期详解:从创建到销毁的全景解析
架构·harmonyos·鸿蒙·鸿蒙系统
颜颜yan_2 天前
深入解析HarmonyOS5 UIAbility组件:从核心架构到实战应用
架构·harmonyos·鸿蒙·鸿蒙系统
Raink老师3 天前
鸿蒙任务项设置案例实战
harmonyos·鸿蒙·案例实战
HarmonyOS小助手5 天前
【鸿蒙生态学堂04】ArkUI开发基础(上)
harmonyos·鸿蒙·harmonyos next·arkui(方舟ui框架)介绍·使用常用组件构建页面·harmonyos 5.0·鸿蒙5·鸿蒙课程·鸿蒙生态
鸿蒙自习室6 天前
鸿蒙UI开发——组件的自适应拉伸
ui·华为·harmonyos·鸿蒙
王二蛋和他的狗7 天前
HarmonyOS运动开发:精准估算室内运动的距离、速度与步幅
鸿蒙
郑知鱼7 天前
【拥抱鸿蒙】HarmonyOS NEXT实现双路预览并识别文字
华为·ocr·harmonyos·鸿蒙·移动端·鸿蒙next·ohos