HarmonyOS鸿蒙Next中ets开发父子组件函数互调: 父组件如何调用子组件方法,子组件如何调用父组件方法
HarmonyOS鸿蒙Next中ets开发父子组件函数互调: 父组件如何调用子组件方法,子组件如何调用父组件方法?
3 回复
在HarmonyOS Next的ArkTS开发中,父子组件方法互调可以通过以下方式实现:
- 父组件调用子组件方法:
- 使用
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();
})
}
}
}
- 子组件调用父组件方法:
- 通过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回调方式适合子组件向父组件通信。