HarmonyOS API 11 中自定义子组件如何调用父组件中的方法?

API 11中自定义子组件可以调用父组件方法吗,该如何实现

阅读 424
1 个回答

可以使用以下demo来实现子组件调用父组件里的方法:

@Entry
@Component
struct Index12 {
  clickFunc(data: number) {
    console.log(data.toString())
  }

  build() {
    Row() {
      Column() {
        child({ click: (data: number): void => this.clickFunc(data) })
      }.width('100%')
    }.height('100%')
  }
}

@Component
export struct child {
  click? = (data: number) => {
  };

  build() {
    Row() {
      Column() {
        Text('点击子组件').onClick(() => {
          if (this.click != undefined) {
            this.click(123);
          }
        })
      }.width('100%')
    }.height('100%')
  }
}