目录

@BuilderParam如何接收父组件的状态变量

问题现象

如何通过@BuilderParam装饰器传递@State装饰的状态变量?

背景知识

@BuilderParam装饰器用于装饰指向@Builder方法的变量,能够声明任意UI描述的元素。@BuilderParam装饰器初始化的值必须为@Builder,否则编译时就会输出报错信息。

解决方案

@State装饰器装饰的变量不可直接传递给@BuilderParam装饰器,可以使用@Builder装饰器当做桥梁,在@Builder装饰的构建函数中使用状态变量,实现状态变量的传递,具体实现如下:

完整示例代码如下:

@Entry
@Component
struct TransmitBuilderParam {
  @State message: string = '状态变量';

  @Builder
  customParBuilder() {
    Text(this.message);
  }

  build() {
    Row() {
      Column({ space: 10 }) {
        MyCustomContainer({
          customView: () => {
            this.customParBuilder();
          }
        });
        Button('修改状态变量')
          .onClick(() => {
            this.message = '12345';
          });
      }
      .width('100%');
    }
    .height('100%');
  }
}

@Component
struct MyCustomContainer {
  @Builder
  customViewBuild() {
  }

  @BuilderParam customView: () => void = this.customViewBuild;

  build() {
    Column() {
      Text('childText');
      this.customView();
    };
  }
}

运行效果图如下: