ArkUI自定义组件父组件如何向子组件传递方法 HarmonyOS 鸿蒙Next
ArkUI自定义组件父组件如何向子组件传递方法 HarmonyOS 鸿蒙Next
针对@Component修饰的父子组件,可以通过对象将父组件的属性和方法传递给子组件,在子组件中接收父组件的属性和方法,并且调用该方法。示例代码如下:
[@Component](/user/Component)
export struct ParentChildComEventTransfer {
@State message: string = '来自父组件的内容';
build() {
Row() {
Column() {
Child({
message: this.message,
onClickOK: (): void => {
console.info('onClickOK action');
}
})
}
.width('100%')
}
.height('100%')
}
}
[@Component](/user/Component)
struct Child {
@Prop message: string;
onClickOK?: () => void;
build() {
Row() {
Column() {
Text(this.message)
Button('事件')
.onClick(() => {
if (this.onClickOK !== undefined) {
this.onClickOK();
}
})
}
.width('100%')
}
.height('100%')
}
}
更多关于ArkUI自定义组件父组件如何向子组件传递方法 HarmonyOS 鸿蒙Next的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
子组件调用父组件方法您可以参考此链接:
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-create-custom-components-V5
更多关于ArkUI自定义组件父组件如何向子组件传递方法 HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在鸿蒙Next中,ArkUI框架支持父组件向子组件传递方法。具体实现步骤如下:
-
定义子组件:在子组件中,使用
@Prop
或@Link
装饰器声明一个函数类型的属性。例如:[@Component](/user/Component) struct ChildComponent { @Prop onEvent: () => void; build() { Button('Click Me').onClick(() => { this.onEvent(); }); } }
-
父组件传递方法:在父组件中,将需要传递的方法绑定到子组件的属性上。例如:
[@Component](/user/Component) struct ParentComponent { build() { Column() { ChildComponent({ onEvent: this.handleEvent.bind(this) }) } } handleEvent() { console.log('Event handled in parent'); } }
-
方法调用:当子组件中的事件触发时,调用父组件传递的方法。
通过这种方式,父组件可以将方法传递给子组件,并在子组件中调用该方法。