鸿蒙ArkTs-子组件如何调用父组件方法

场景:页面加载数据失败时,子组件有个【重新加载】按钮,点击后,执行父组件的获取数据方法。

1:在子组件中添加一个回调方法

// 空数据提示
@Component
export struct  Nodata{
  // 接收父组件传递的方法
  callParent? = () => {  };
  @Link isLoading:boolean
  build() {
    if(this.isLoading){
      Column() {
        LoadingProgress()
          .width(60)
          .height(60)
          .color($r('app.color.green2'))
      }
      .width('100%')
      .height('100%')
      .justifyContent(FlexAlign.Center)
    }else {
      Column({space:24}) {
        Image($r('app.media.panda_skip_logo'))
          .width(64)
          .height(64)
          .borderRadius(20)
        Text('页面加载失败,请稍后重试')
          .fontSize(14)
          .fontColor($r('sys.color.ohos_id_color_text_tertiary'))
        Button('重新加载')
          .onClick(()=>{
            // 调用父组件方法
            this.callParent!();
            this.isLoading=true
          })
          .fontSize(14)
          .fontWeight(FontWeight.Normal)
          .fontColor($r('sys.color.ohos_id_color_text_primary'))
          .backgroundColor('transparent')
          .borderWidth(1)
          .borderColor($r('sys.color.ohos_id_color_text_tertiary'))
      }
      .width('100%')
      .height('100%')
      .justifyContent(FlexAlign.Center)
    }

  }
}

2:父组件中的方法做为参数传递进去

if(this.personalProfile){
  // 可滚动的容器组件,当子组件的布局尺寸超过父组件的尺寸时,内容可以滚动。
  。。。
}else {
  Nodata({callParent:this.dataGet.bind(this),isLoading:this.isLoading})
}

3:this.dataGet.bind(this) 和this.dataGet 使用效果

效果:直接传递函数引用,但不绑定父组件的上下文(即父组件的 this)。当子组件调用该方法时,函数内部的 this指向子组件自身,而非父组件。


问题:若父组件方法中访问了父组件的状态(如 this.stateValue)或方法,会因 this指向错误而报错(例如 undefined is not an object)。

适用场景:父组件方法 不依赖父组件内部状态(例如纯工具函数)。

刚才例子,我的父组件方法涉及状态操作(如修改 @State变量),必须使用 bind(this)确保上下文正确。传递方法时优先显式绑定,避免潜在错误。