自学鸿蒙HarmonyOS的ArkTS语言<十>@BuilderParam装饰器

作用:当子组件多处使用时,给某处的子组件添加特定功能

一、初始化

1、只能被@Builder装饰的方法初始化

2、使用所属自定义组件的@builder方法初始化

3、使用父组件的@builder方法初始化 - 把父组件的@builder传过去,参数名和子组件的@builderParam同名

java 复制代码
@Component
struct Child {
  @Builder childBuilder() {}
  @BuilderParam childBuilderParam: () => void = this.childBuilder // 必须用childBuilder初始化下,否则预览出不来

  build() {
    Column() {
      Text('我是子组件')
        .fontColor(Color.White)
      this.childBuilderParam()
    }
  }
}

@Entry
@Component
struct Index7 {

  @Builder parentBuilder() {
    Text('我是父组件定制的的 builder')

  }

  build() {
    Column() {
      Row() {
        Child({childBuilderParam: this.parentBuilder}) // 添加独特功能
      }
      .padding(10)
      .backgroundColor(Color.Brown)

      Row() {
        Child()
      }
      .padding(10)
      .backgroundColor(Color.Green)

    }
  }
}
二、this指向
java 复制代码
@Component
struct Child1 {
  label: string = '我是子组件的label'
  @Builder childBuilder() {}
  @BuilderParam childBuilderParam: () => void = this.childBuilder
  @BuilderParam childChangeThisBuilderParam: () => void = this.childBuilder

  build() {
    Column() {
      this.childBuilderParam()
      this.childChangeThisBuilderParam()
    }
  }
}

@Entry
@Component
struct Index7_1 {
  label: string = '我是父组件的label'

  @Builder parentBuilder() {
    Text(this.label)

  }

  build() {
    Column() {
      this.parentBuilder() // this指向父组件


      Child1({
        childBuilderParam: this.parentBuilder, // this.parentBuilder传入到child中指向child
        childChangeThisBuilderParam: (): void => this.parentBuilder(), // 箭头函数的this指向宿主对象,即父组件
      })

    }
  }
}
三、带参数
java 复制代码
class Tmp {
  label: string = ''
}
// 全局builder
@Builder function globalBuilder($$: Tmp) {
  Text($$.label)
}

// Child1中
...
// 有参数
@BuilderParam childHasParamsBuilderParam: ($$: Tmp) => void = globalBuilder
build() {
  Column() {
	  ...
	  this.childHasParamsBuilderParam({label: '我是一个有参数的BuilderParam'})
  }
}
// 父组件中
...
Child1({
  ...
  childHasParamsBuilderParam: globalBuilder
})
四、尾随闭包的形式
java 复制代码
@Component
struct Child2 {
  @Builder childBuilder() {}
  // 尾随闭包的形式传入时子组件内只能有一个BuilderParam
  @BuilderParam childBuilderParam: () => void = this.childBuilder

  build() {
    Column() {
      Text('我是子组件2')
      this.childBuilderParam()
    }
    .margin({top: 30})
  }
}
// 父组件中
...
Child2() {
   Column() {
     globalBuilder({label: '我是通过尾随闭包传入的'})
   }
}

注意:

尾随闭包的形式子组件内只能有一个 @BuilderParam

相关推荐
Cheney82240 分钟前
华为Ai岗机考20250903完整真题
人工智能·华为
用户7227868123443 小时前
HarmonyOS实现快递APP自动识别地址
harmonyos
企业软文推广4 小时前
奥迪A5L×华为:品牌营销视角下的燃油车智能突围战!
python·华为
爱笑的眼睛114 小时前
HarmonyOS声明式UI开发:深入探索ArkUI与Stage模型
华为·harmonyos
爱笑的眼睛114 小时前
HarmonyOS应用开发:深入理解声明式UI与弹窗交互的最佳实践
华为·harmonyos
Cobboo4 小时前
HarmonyOS 5.1.1版本图片上传功能
华为·harmonyos
爱笑的眼睛1114 小时前
HarmonyOS 应用开发新范式:深入探索 Stage 模型与 ArkUI 声明式开发
华为·harmonyos
光锥智能18 小时前
小平板元年,华为MatePad Mini创出一片蓝海
华为·电脑
祥睿夫子18 小时前
零基础搞定 ArkTS 类与对象!保姆级教程:定义→创建→测试全流程 + 代码示例
harmonyos