在HarmonyOS NEXT开发中父组件如何触发子组件内定义的方法?
在HarmonyOS NEXT的ArkUI框架中,父组件触发子组件方法的常见方式有两种:
Ref
引用// 子组件
@Component
struct ChildComponent {
@State message: string = "Hello"
// 需要暴露的方法
myChildMethod(param: string) {
this.message = param
}
build() {
Text(this.message)
}
}
// 父组件
@Entry
@Component
struct ParentComponent {
// 1. 创建子组件引用
@State childRef: Ref<ChildComponent> = Ref()
build() {
Column() {
// 2. 绑定组件引用
ChildComponent({ ref: this.childRef })
Button('触发子组件方法')
.onClick(() => {
// 3. 通过引用调用子组件方法
this.childRef.value?.myChildMethod('Updated!')
})
}
}
}
// 子组件
@Component
struct ChildComponent {
// 1. 声明回调函数属性
@Prop onParentTrigger!: () => void
myChildMethod() {
// 子组件内部逻辑
}
build() {
Button('子组件按钮')
.onClick(() => {
this.onParentTrigger()
})
}
}
// 父组件
@Entry
@Component
struct ParentComponent {
// 2. 创建子组件引用
private childRef: Ref<ChildComponent> = Ref()
build() {
Column() {
ChildComponent({
// 3. 传递回调函数
onParentTrigger: () => {
this.childRef.value?.myChildMethod()
},
ref: this.childRef
})
}
}
}
建议:优先使用回调函数方式保持组件独立性,仅在必要时使用Ref直接操作子组件。
可以定义一个controller类,在controller类中定义和子组件中类型相同的方法,在子组件中将实际封装的方法给到controller。
父组件在使用时,new一个controller对象然后转入子类中,在父组件中调用controller对应的方法即可。参考示例如下: