@Builder
ArkUI提供了一种更轻量的UI元素复用机制 @Builder,可以将重复使用的UI元素抽象成一个方法,在 build 方法里调用。
@Entry
@Component
struct Parent {
label: string = `Parent`
@Builder componentBuilder() {
Text(`${this.label}`)
}
build() {
Column() {
this.componentBuilder()
}
}
}
效果图
@Buider可支持组件内和全局写法
@Builder function overBuilder() {} // 全局定义
@Component
struct Child {
@Builder doNothingBuilder() {}; // 组件内定义
build(){
Column(){
overBuilder() // 组件内使用全局Builder
this.doNothingBuilder() // 使用组件内Builder
}
}
}
@BuilderParam装饰器
@BuilderParm可接收组件,类似vue的slot
尾随闭包
@Component
struct QfBlackButton {
@BuilderParam DefaultContent: () => void
build() {
Row() {
this.DefaultContent()
}
}
}
// 父组件调用
QfBlackButton() {
Text('21312321)
}
注意!!!@BuilderParam装饰的方法,默认值只能是被@Builder装饰的方法
@Component
struct Child {
@Builder customBuilder() {}
// 使用父组件@Builder装饰的方法初始化子组件@BuilderParam
@BuilderParam customBuilderParam: () => void = this.customBuilder;
@BuilderParam textBuilderParam: () => void;
build() {
Column() {
this.customBuilderParam()
}
}
}
@Entry
@Component
struct Parent {
@Builder componentBuilder() {
Text(`Parent builder `)
}
@Builder textBuilder() {
Text(`Text builder `)
}
build() {
Column() {
// 传入多个组件时最好具名传入
Child({ customBuilderParam: this.componentBuilder, textBuilderParam: this.textBuilder() })
}
}
}
@BuilderParam接收@Builder后this指针问题
官网中有一段话叫:
需注意this指向正确。
以下示例中,Parent组件在调用this.componentBuilder()时,this指向其所属组件,即“Parent”。@Builder componentBuilder()通过this.componentBuilder的形式传给子组件@BuilderParam customBuilderParam,this指向在Child的label,即“Child”。@Builder componentBuilder()通过():void=>{this.componentBuilder()}的形式传给子组件@BuilderParam customChangeThisBuilderParam,因为箭头函数的this指向的是宿主对象,所以label的值为“Parent”。
@Component
struct Child {
label: string = `Child`
@Builder customBuilder() {}
@Builder customChangeThisBuilder() {}
@BuilderParam customBuilderParam: () => void = this.customBuilder;
@BuilderParam customChangeThisBuilderParam: () => void = this.customChangeThisBuilder;
build() {
Column() {
this.customBuilderParam()
this.customChangeThisBuilderParam()
}
}
}
@Entry
@Component
struct Parent {
label: string = `Parent`
@Builder componentBuilder() {
Text(`${this.label}`)
}
build() {
Column() {
this.componentBuilder()
Child({ customBuilderParam: this.componentBuilder, customChangeThisBuilderParam: ():void=>{this.componentBuilder()} })
}
}
}
也就是说在父组件定义的Builder函数内如果想继续使用父组件的this需要这样给子组件传
// 使用箭头函数传入这样this会存在定义的上下文中
Child({ customChangeThisBuilderParam: ():void=>{this.componentBuilder()} })