鸿蒙NEXT 自定义组件封装,@BuilderParam使用

290 阅读1分钟

当我们需要封装一个需要从外部动态传入的组件时,可以使用@BuilderParam裝飾器。 如封裝一个页面,顶部和底部样式固定不变,中间会根据不同需求需要动态传入时,类似如图

Screenshot_2024-08-28T011357.png

实现:

@ComponentV2
struct MyComponent {
  @Builder
  customBuilder() {
  };

  // 使用父组件@Builder装饰的方法初始化子组件@BuilderParam
  @BuilderParam myComponent: () => void = this.customBuilder;

  @LocalBuilder
  TopView() {
    Text('顶部').padding(10).backgroundColor(Color.Red).width('100%')
      .textAlign(TextAlign.Center)
  }

  @LocalBuilder
  BottomView() {
    Text('底部').padding(10).backgroundColor(Color.Red).width('100%')
      .textAlign(TextAlign.Center)
  }

  build() {
    Column() {
      this.TopView()
      this.myComponent()
      this.BottomView()
    }.width('100%').height('100%').justifyContent(FlexAlign.SpaceAround)
  }
}

调用处:

@Entry
@Component
struct TestPage {
    
  //传入自定义组件的动态组成部分
  @Builder
  customView() {
    Text(`custom view `).backgroundColor(Color.Blue).layoutWeight(1).width('100%')
      .textAlign(TextAlign.Center)
  }

  build() {
    Column() {
      MyComponent({ myComponent: this.customView }) 
    }
  }
}