作用:当子组件多处使用时,给某处的子组件添加特定功能
一、初始化
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)
- }
- }
- }
复制代码 二、this指向
- @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
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |