概述
利用 @BuilderParam 构建函数,可以将外部的 UI 组件传递给自定义的组件,即UI组件可以作为参数传递。
talk is cheap, show me the code
自定义的组件(等待接收参数的组件)
@Component
export default struct TestBuilderParamComponent {
@BuilderParam
contentBuilders: () => void = this.defaultBuilders
@Builder
defaultBuilders() {
Text('这是个默认文本')
.fontColor(Color.Black)
.fontSize(20)
}
build() {
Column() {
this.contentBuilders()
}
}
}
传递参数的组件(传递参数的组件)
import TestBuilderParamComponent from '../components/TestBuilderParamComponent';
@Entry
@Component
struct Index {
build() {
Column({ space: 20 }) {
TestBuilderParamComponent()
TestBuilderParamComponent() {
Text('这是个传入的值')
.fontColor(Color.Red)
.fontSize(30)
}
TestBuilderParamComponent() {
Image($r('app.media.app_icon'))
.width(160)
.height(160)
}
}
.backgroundColor('#F1F3F5')
.height('100%')
.width('100%')
}
}
效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/12046b55e1d24cf98cebb44ac478277c.png#pic_center)
需要传递多个 BuilderParam 参数
自定义的组件(等待接收参数的组件)
@Component
export default struct TestBuilderParamComponent {
@BuilderParam
titleBuilders: () => void = this.defaultBuilders
@BuilderParam
contentBuilders: () => void = this.defaultBuilders
@Builder
defaultBuilders() {
Text('这是个默认文本')
.fontColor(Color.Black)
.fontSize(20)
}
build() {
Column() {
this.titleBuilders()
this.contentBuilders()
}
}
}
传递参数的组件(传递参数的组件)
import TestBuilderParamComponent from '../components/TestBuilderParamComponent';
@Entry
@Component
struct Index {
@Builder
titleBuilders() {
Text('我是多参数BuilderParam标题')
}
@Builder
contentBuilders() {
Text('我是多参数BuilderParam内容')
}
build() {
Column({ space: 20 }) {
TestBuilderParamComponent({
titleBuilders: this.titleBuilders,
contentBuilders: this.contentBuilders
})
}
.padding({ top: 50 })
.backgroundColor('#F1F3F5')
.height('100%')
.width('100%')
}
}
多BuilderParam的效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/c49409cc15c24ab4a47ee3b158e31712.png#pic_center)