自定义两个父子组件,在父组件中声明了一个@Builder装饰的私有自定义构建函数并传递给子组件,子组件通过@BuilderParam装饰器接收父组件传递的@Builder函数并使用,存在自定义构建函数被子组件调用后,Text组件内容不显示的问题,问题代码示例参考如下:
// 父组件 @Entry @Component struct Index { @State message: string = 'Hello World'; @Builder contentComponent() { Row() { Text(this.message) .fontSize(15) .fontWeight(FontWeight.Bold) .onClick(() => { this.message = 'Welcome'; }); } .backgroundColor(Color.Gray) .borderRadius(10) .justifyContent(FlexAlign.Center) .width('90%') .height(50); } build() { RelativeContainer() { SectionView({ title: '第一章', contentView: this.contentComponent }); } .height('100%') .width('100%'); } } // 子组件 @Component export struct SectionView { @Prop title: string = ''; @Builder defaultContentView() { } @BuilderParam contentView: () => void = this.defaultContentView; build() { Column({ space: 10 }) { Text(this.title) .fontSize(16) .width('100%') .textAlign(TextAlign.Center); this.contentView(); } .backgroundColor(Color.White); } }
问题效果预览:

全局自定义构建函数 | 私有自定义构建函数 |
|---|---|
若需要传入的参数不是全局变量,是@Component自定义组件内的变量时,必须在调用时通过函数的参数传递的方式获取构建UI需要的数据。 | 由于私有自定义构建函数是@Component组件内定义的,所以在@Component组件调用私有自定义构建函数时,可以不通过函数的参数传递方式,直接采用this指针,指向调用时所在的@Component组件变量。 |
本地运行代码,没有报错信息,@Builder函数被成功调用,但是内部的Text文本未显示,推测是传入自定义组件的参数值有问题,通过debug发现contentComponent方法中this.message的值为undefined。

调用子组件传入contentView: this.contentComponent参数时,contentComponent组件构建函数中this指向的是子组件SectionView,相当于在子组件中使用了this.message,而子组件中没有message这个变量,所以调试显示为undefined,从而导致内容不生效。
build() { RelativeContainer() { OptionOneSectionView({ title: '第一章', contentView: () => { this.contentComponent(); } }); } .height('100%') .width('100%'); }
@Entry @Component struct OptionTwoIndex { @State message: string = 'Hello World'; @LocalBuilder contentComponent() { Row() { Text(this.message) .fontSize(15) .fontWeight(FontWeight.Bold) .onClick(() => { this.message = 'Welcome'; }); } .backgroundColor(Color.Gray) .borderRadius(10) .justifyContent(FlexAlign.Center) .width('90%') .height(50); } build() { RelativeContainer() { OptionTwoSectionView({ title: '第一章', contentView: this.contentComponent }); } .height('100%') .width('100%'); } }