HarmonyOS @BuilderParams尾随闭包方式能否传递参数

在尾随闭包的使用说明里没看到说不能传递参数的,那么使用的时候是否可以传参,怎么获取传递的参数?

@Component
struct MyComponent {
  build() {
    TestBuild({
      arg: "hello"
    }) {
      //#3 ??这边能否获取父组件调用时传递的参数??
      Text()
    }
  }
}

@Component
struct TestBuild {
  //#1 定义一个有参数的BuilderParam
  @BuilderParam content: (arg: string) => void
  @State arg: string = ""

  build() {
    Column() {
      //#2 调用的时候传递参数
      this.content(this.arg)

      Button("change Arg")
        .margin({ top: 24 })
        .onClick(() => {
          this.arg = "change!!"
        })
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
HarmonyOS
2024-12-23 15:40:38
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280

父组件在调用MyComponent组件时,只需要在MyComponent组件中使用@Prop来接受父组件传递的参数即可:

@Component
struct CustomContainer {
  @Prop header: string = '';

  @Builder
  closerBuilder() {
  }

  // 使用父组件的尾随闭包{}(@Builder装饰的方法)初始化子组件@BuilderParam
  @BuilderParam closer: () => void = this.closerBuilder

  build() {
    Column() {
      Text(this.header)
        .fontSize(30)
      this.closer()
    }
  }
}

@Builder
function specificParam(label1: string, label2: string) {
  Column() {
    Text(label1)
      .fontSize(30)
    Text(label2)
      .fontSize(30)
  }
}

@Entry
@Component
struct CustomContainerUser {
  @State text: string = 'header';

  build() {
    Column() {
      // 创建CustomContainer,在创建CustomContainer时,通过其后紧跟一个大括号“{}”形成尾随闭包
      // 作为传递给子组件CustomContainer @BuilderParam closer: () => void的参数
      CustomContainer({ header: this.text }) {
        Column() {
          specificParam('testA', 'testB')
        }.backgroundColor(Color.Yellow)
        .onClick(() => {
          this.text = 'changeHeader';
        })
      }
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
分享
微博
QQ
微信
回复
2024-12-23 17:34:40
相关问题
class使用方式初始化 默认值丢失
2645浏览 • 1回复 待解决
HarmonyOS 关于的问题
956浏览 • 1回复 待解决
如何在ArkTS中使用
1533浏览 • 1回复 待解决
HarmonyOS har能否引用tgz
939浏览 • 1回复 待解决
HarmonyOS rest参数如何传递
920浏览 • 1回复 待解决
HarmonyOS @Prop参数传递问题
758浏览 • 1回复 待解决
HarmonyOS web组件参数传递报错
1031浏览 • 1回复 待解决
HarmonyOS http post请求参数传递
1092浏览 • 1回复 待解决
HarmonyOS rcp请求如何传递参数
810浏览 • 1回复 待解决
HarmonyOS 能否通过eventHub传递Want数据
591浏览 • 1回复 待解决
router传递hashmap参数问题
2537浏览 • 1回复 待解决
HarmonyOS router参数不能传递函数
576浏览 • 1回复 待解决