API 12
@Builder
传递参数方式有两种1 引用传递参数 2 值传递
引用传递参数
class Tmp {
paramA1: string = ''
}
@Builder function overBuilder(params: Tmp) {
Row() {
Text(`UseStateVarByReference: ${params.paramA1} `)
}
}
@Entry
@Component
struct Parent {
@State label: string = 'Hello';
build() {
Column() {
// Pass the this.label reference to the overBuilder component when the overBuilder component is called in the Parent component.
overBuilder({ paramA1: this.label })
Button('Click me').onClick(() => {
// After Click me is clicked, the UI text changes from Hello to ArkUI.
this.label = 'ArkUI';
})
}
}
}
值传递
调用@Builder装饰的函数默认按值传递。当传递的参数为状态变量时,状态变量的改变不会引起@Builder方法内的UI刷新。
@Builder function overBuilder(paramA1: string) {
Row() {
Text(`UseStateVarByValue: ${paramA1} `)
}
}
@Entry
@Component
struct Parent {
@State label: string = 'Hello';
build() {
Column() {
overBuilder(this.label)
}
}
}
@BuilderParam用来装饰指向@Builder方法的变量
@BuilderParam装饰的方法只能被自定义构建函数(@Builder装饰的方法)初始化。
使用所属自定义组件的自定义构建函数或者全局的自定义构建函数,在本地初始化@BuilderParam。
@Builder function overBuilder() {}
@Component
struct Child {
@Builder doNothingBuilder() {};
// 使用自定义组件的自定义构建函数初始化@BuilderParam
@BuilderParam customBuilderParam: () => void = this.doNothingBuilder;
// 使用全局自定义构建函数初始化@BuilderParam
@BuilderParam customOverBuilderParam: () => void = overBuilder;
build(){}
}
用父组件自定义构建函数初始化子组件@BuilderParam装饰的方法。
@Component
struct Child {
@Builder customBuilder() {}
// 使用父组件@Builder装饰的方法初始化子组件@BuilderParam
@BuilderParam customBuilderParam: () => void = this.customBuilder;
build() {
Column() {
this.customBuilderParam()
}
}
}
@Entry
@Component
struct Parent {
@Builder componentBuilder() {
Text(`Parent builder `)
}
build() {
Column() {
Child({ customBuilderParam: this.componentBuilder })
}
}
}
如果对大家有帮助,希望一键三连哟!