参考代码:import { BusinessError } from "@ohos.base"; import { HashMap } from '@kit.ArkTS'; import map from '@hms.core.map.map'; @Component struct Child { @Builder customBuilder() { } // 使用父组件@Builder装饰的方法初始化子组件@BuilderParam @BuilderParam customBuilderParam: () => void = this.customBuilder; build() { Column() { this.customBuilderParam() } } } @Entry @Component struct Index45 { @State message: string = 'Hello World'; @State keys: number = 1 @Builder component1() { Column() { Text('component0') .width(100) .backgroundColor(Color.Red) } .width('100%') } @Builder component2() { Column() { Text('component1') .width(100) .backgroundColor(Color.Red) } .width('100%') } @Builder component3() { Column() { Text('component2') .width(100) .backgroundColor(Color.Red) } .width('100%') } build() { Column({ space: 30 }) { Text('显示component1') .fontSize(20) .fontWeight(FontWeight.Bold) .onClick(() => { this.keys = 0 }) Text('显示component2') .fontSize(20) .fontWeight(FontWeight.Bold) .onClick(() => { this.keys = 1 }) Text('显示component3') .fontSize(20) .fontWeight(FontWeight.Bold) .onClick(() => { this.keys = 2 }) if (this.keys === 0) { Child({ customBuilderParam: this.component1 }) } else if (this.keys === 1) { Child({ customBuilderParam: this.component2 }) } else { Child({ customBuilderParam: this.component3 }) } } .height('100%') .width('100%') } }
参考代码: