一、参数初始化组件
@BuilderParam装饰的方法可以是有参数和无参数的两种形式,需与指向的@Builder方法类型匹配
1、定义一个类作为参数
// 定义一个对象,ui需要的数据 export class ViewEntity{ content:string = "sssss"; }
2、定义一个自定义组件
import { ViewEntity } from "../animation/ViewEntity"; // 自定义组件 @Component export struct CommonView{ label: string = 'Child'; @Builder customBuilder() {}; @Builder customerParmsBuilder($$:ViewEntity){} // 无参数类型,指向的componentBuilder也是无参数类型 @BuilderParam customBuilderParam: () => void = this.customBuilder; // 有参数类型,指向的overBuilder也是有参数类型的方法 @BuilderParam customOverBuilderParam: ($$: ViewEntity) => void = this.customerParmsBuilder; build() { Column() { this.customBuilderParam() this.customOverBuilderParam(new ViewEntity() ) } } }
3、有参和无参两种使用自定义组件的方式
/** * @author : xqx * @create_day : 2024/11/21 * @description : 首页 */ import { HMRouter } from "@hadss/hmrouter"; import { ViewEntity } from "../animation/ViewEntity"; import { CommonView } from "../components/CommonView"; @HMRouter({ pageUrl: 'Main', singleton: true, lifecycle: 'ExitAppLifecycle', animator: 'pageAnimator' }) @Component export struct Main { label: string = '使用组件的Parent'; viewEntity : ViewEntity = new ViewEntity() aboutToAppear(): void { this.viewEntity.content = "类的content字段" } // 无参自定义组件构建函数 @Builder componentBuilder() { Text(`${this.label}`) } // 有参自定义组件构建函数 @Builder componentParmsBuilder($$: ViewEntity) { Text($$.content) .width(400) .height(50) .backgroundColor(Color.Red) } build() { Column() { // 显示当前自定义构建函数 ,所以显示文案为 使用组件的Parent this.componentBuilder() Divider() // 使用一个自定义组件,通过@BuilderParms装饰器 传入当前 componentBuilder和componentParmsBuilder两个构建函数 // 传入的无参构建函数componentBuilder,显示 label内容,在CommonView里面定义的内容为Child,所以显示Child // 传入的有参构建函数componentParmsBuilder,参数为一个ViewEntity类的对象,内容为显示对象的content属性值,因为自定义组件内new ViewEntity,且content字段默认值为sssss,所以ui显示未sssss CommonView({ customBuilderParam: this.componentBuilder, customOverBuilderParam: this.componentParmsBuilder }) } } }
效果图:
标签:初始化,componentBuilder,自定义,BuilderParam,组件,参数,ViewEntity,四十三,content From: https://www.cnblogs.com/xqxacm/p/18565281