可以定义一个controller类,在controller类中定义和子组件中类型相同的方法,在子组件中将实际封装的方法给到controller。父组件在使用时,new一个controller对象然后转入子类中,在父组件中调用controller对应的方法即可。
参考代码如下:
@Component
struct Child {
@State private text: string = '初始值';
private controller: ChildController = new ChildController();
aboutToAppear() {
if (this.controller) {
//给controller对应的方法赋值
this.controller.changeText = this.changeText;
}
}
private changeText = (value: string) => {
this.text = value;
}
build() {
Column() {
Text(this.text)
}
}
}
//定义controller对象
class ChildController {
changeText = (value: string) => {
}
}
@Entry
@Component
struct Parent {
private ChildRef = new ChildController();
build() {
C