参考demo:
1、两个子组件通过@Link关联父组件用@State修饰的状态变量,再用@Watch监听状态变量变化,可以实现在组件b里调用组件a里的方法,但是@State修饰的变量变化会引起界面的刷新,请参考如下demo
@Entry
@Component
struct Index {
[@State](/user/State) msg: string = "组件消息"
build() {
Column() {
Text("page Index").fontSize(50).fontWeight(FontWeight.Bold)
ComponentA({ msg: this.msg })
ComponentB({ msg: this.msg })
}
}
}
@Component
export struct ComponentB {
[@Watch](/user/Watch)("changeData") [@Link](/user/Link) msg: string
changeData() {
console.log("ComponentB change")
}
build() {
Text(this.msg).fontSize(50).fontWeight(FontWeight.Bold)
}
}
@Component
export struct ComponentA {
[@Link](/user/Link) msg: string
build() {
Column() {
Text(this.msg).fontSize(50).fontWeight(FontWeight.Bold)
Button("ComponentB change").onClick(() => {
this.msg = "更新数据"
})
}
}
}
2、也可以定义一个类Mid,在类中定义方法midFunc,在父组件中new一个类的实例传入子组件a中,在a的aboutToAppear方法中将需要在其他组件中执行的方法赋值给mid.midFunc,然后在父组件中创建b组件的时候把b组件中的x方法重写为mid.midFunc(),这样在b中调用x方法时实际执行的是组件a中的方法。
请参考如下示例代码:
@Entry
@Component
struct Index {
[@State](/user/State) msg: string = "组件消息"
//midFunc:Function=()=>"qtw index midFunc";
mid:Mid=new Mid();
build() {
Column() {
Text("page Index").fontSize(50).fontWeight(FontWeight.Bold)
ComponentB({mid:this.mid})
ComponentA({changeData:()=>{this.mid.midFunc()}})
}
}
}
@Component
export struct ComponentB {
[@State](/user/State) msg:string='组件B';
//midFunc:Function=()=>"qtw ComponentB midFunc";
mid:Mid=new Mid();
changeData: Function = () => {
this.msg='变更B数据'
console.log("qtw ComponentB change")
}
aboutToAppear(){
console.log(`qtw constructor`)
this.mid.midFunc=this.changeData;
}
build() {
Text(this.msg).fontSize(50).fontWeight(FontWeight.Bold)
}
}
@Component
export struct ComponentA {
[@State](/user/State) msg:string='组件A';
changeData: Function = () => {
this.msg='变更A数据'
console.log("qtw ComponentA change")
}
build() {
Column() {
Text(this.msg).fontSize(50).fontWeight(FontWeight.Bold)
Button("A中的按钮").onClick(() => {
this.changeData();
})
}
}
}
class Mid{
midFunc:Function=(){};
}