HarmonyOS NEXT学习——@BuilderParam装饰器

发布于:2024-07-18 ⋅ 阅读:(152) ⋅ 点赞:(0)

初步理解,相当于VUE的插槽slot


@Builder function overBuilder() {}

@Component
struct Child {
  label: string = `Child`
  @Builder customBuilder() {}
  @Builder customChangeThisBuilder() {}
  @BuilderParam customBuilderParam: () => void = this.customBuilder; // 使用自定义组件的自定义构建函数初始化@BuilderParam
  @BuilderParam customChangeThisBuilderParam: () => void = this.customChangeThisBuilder; // 使用自定义组件的自定义构建函数初始化@BuilderParam
  @BuilderParam customOverBuilderParam: () => void = overBuilder; // 使用全局自定义构建函数初始化@BuilderParam
  build() {
    Column() {
      this.customBuilderParam()
      this.customChangeThisBuilderParam()
      this.customOverBuilderParam()
    }
  }
}

@Entry
@Component
struct Parent {
  label: string = `Parent`
  button: string =`are you ok??`
  
  @Builder componentBuilder() {
    Text(`${this.label}`)
      .fontSize(50)
  }
  @Builder customChangeOverBuilderParam(){
  	Button(this.label)
  }

  build() {
    Column() {
      Child({ customBuilderParam: this.componentBuilder }) //this指向的是Parent的componentBuilder,componentBuilder里的this指向的是Child,所以label的值为“Child”
      Child({ customChangeThisBuilderParam: ():void=>{this.componentBuilder()}}) //通过():void=>{this.componentBuilder()}的形式传给子组件,因为箭头函数的this指向的是宿主对象,所以label的值为“Parent”
      Child({ customBuilderParam: this.componentBuilder,customChangeThisBuilderParam: ():void=>{this.componentBuilder()},customOverBuilderParam:():void=>{this.customChangeOverBuilderParam()}}) //正确组合写法,上面两条分别调Child为了区分
    }
  }

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到