HarmonyOS鸿蒙Next中ets开发父子组件函数互调: 父组件如何调用子组件方法,子组件如何调用父组件方法

HarmonyOS鸿蒙Next中ets开发父子组件函数互调: 父组件如何调用子组件方法,子组件如何调用父组件方法?

3 回复

子组件调用父组件的方法:

父组件传递函数给子组件,通过Lambda闭包传递函数,子组件可以能够获取到父组件传递的函数,并调用成功:

@Component
struct Child {
  @Builder
  customBuilder() {
    
  }
  @BuilderParam childBuilder:()=>"void"
  @State btnText:string = "child btn"
  build() {
    Column() {
      Text("child")
      this.childBuilder()
    }
  }
}

@Entry
@Component
struct Parent {
  @State btnTxt:string = "parent btn"
  parentBtnClickFn() {
    console.log("click parrent")
  }
  
  @Builder
  parrentBuilder() {
    Button(this.btnTxt)
      .onClick(()=>{
        this.parentBtnClickFn()
      })
  }
  
  build() {
    Column() {
      Text('parrent')
      Child({
        childBuilder: ()=>{
          this.parrentBuilder()
        }
      })
    }
  }
}

更多关于HarmonyOS鸿蒙Next中ets开发父子组件函数互调: 父组件如何调用子组件方法,子组件如何调用父组件方法的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,父组件通过@Provide@Consume装饰器与子组件进行数据交互,父组件可以调用子组件的方法。子组件通过@Link@Prop装饰器接收父组件传递的数据或方法,子组件可以通过this.$emit触发父组件的方法。具体实现需在父组件中定义方法并通过@Provide暴露,子组件通过@Consume@Link接收并调用。

在HarmonyOS Next的ArkTS开发中,父子组件方法互调可以通过以下方式实现:

  1. 父组件调用子组件方法:
  • 使用ref绑定子组件实例
// 子组件
@Component
struct ChildComponent {
  childMethod() {
    console.log('子组件方法被调用');
  }
}

// 父组件
@Component
struct ParentComponent {
  @State childRef: ChildComponent = null;

  build() {
    Column() {
      ChildComponent({ ref: this.childRef })
      Button('调用子组件方法')
        .onClick(() => {
          this.childRef?.childMethod();
        })
    }
  }
}
  1. 子组件调用父组件方法:
  • 通过props传递回调函数
// 父组件
@Component
struct ParentComponent {
  parentMethod() {
    console.log('父组件方法被调用');
  }

  build() {
    Column() {
      ChildComponent({ callback: this.parentMethod.bind(this) })
    }
  }
}

// 子组件
@Component
struct ChildComponent {
  @Prop callback: () => void;

  build() {
    Button('调用父组件方法')
      .onClick(() => {
        this.callback?.();
      })
  }
}

这两种方式分别适用于不同场景,ref方式适合父组件主动调用子组件,而props回调方式适合子组件向父组件通信。

回到顶部