作用:当子组件多处使用时,给某处的子组件添加特定功能
1、只能被@Builder装饰的方法初始化
2、使用所属自定义组件的@builder方法初始化
3、使用父组件的@builder方法初始化 - 把父组件的@builder传过去,参数名和子组件的@builderParam同名
@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) } } }
@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指向宿主对象,即父组件 }) } } }
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 })
@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