鸿蒙OS开发实例:【装饰器-@BuilderParam】

背景

这是一个基础概念,其实没有什么原因,练习过程中,自然可以感受到其用法,后期加上真实项目的演练,会形成习惯

功能核心理念

“在自定义组件中添加一个点击跳转操作。若直接在组件内嵌入事件方法,将会导致所有引入该自定义组件的地方均增加了该功能。为解决此问题,ArkUI引入了@BuilderParam装饰器”

这样的场景在任何平台任何公司都会遇到,是否采用在公共组件中定义某个功能还是在外部定义某个功能,都是取决于实际业务场景发生的概率。

@BuilderParam 要告知是:HarmonyOS有应对这样的机制

核心代码

@Entry
@Component
struct BuilderParam2Index {
  label: string = 'Parent'

  @Builder GlobalBuilder1($$: { label: string }) {
    Text(`${this.label}`).fontColor(Color.White)

    Text($$.label)
      .fontColor(Color.White)
      .width('100%')
      .height(50)
      .backgroundColor(Color.Green)
  }

  build() {
    Column({ space: 30 }) {

      //一. 通过参数初始化组件
      BuilderParamChild2({ aBuilder1: this.GlobalBuilder1 })

      BuilderParamChild2({ label: 'Child', aBuilder1: this.GlobalBuilder1 })

      //二. 通过尾随闭包初始化组件, 如果组件中包含两个及以上@BuilderParam函数,则无法使用此种初始化方式
      BuilderParamChild2(){}

      BuilderParamChild2({ label: 'Child' }) {}

      BuilderParamChild2({ label: 'Child' }) {
        this.GlobalBuilder1({ label: 'global Builder label2' })
      }

      BuilderParamChild2({ label: 'Child' }) {
        Text('自定义初始化文字').fontColor(Color.Orange)
      }

    }
    .width('100%')
    .height('100%')
    .padding({ top: px2vp(111) })
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
  }
}


@Component
struct BuilderParamChild2 {
   label: string = "Child"
  // 有参数类型,指向的GlobalBuilder1也是有参数类型的方法
  @BuilderParam aBuilder1: ($$: { label: string }) => void;

  build() {
    Column() {

      Text('BuilderParamChild').fontColor(Color.Red)
  
      this.aBuilder1({ label: 'global Builder label' })

    }.width('100%').backgroundColor(Color.Green)
  }
}
posted @ 2024-05-20 15:17  烧脑猴  阅读(4)  评论(0编辑  收藏  举报
鸿蒙NEXT文档资料 mau123789是助理v直接可拿取