HarmonyOS鸿蒙Next中父组件直接调用子组件的方法

HarmonyOS鸿蒙Next中父组件直接调用子组件的方法

子组件:

@Component
export struct Child{
......

   hello(){}
}

父组件:

@Component
export struct Parent{
......

   build(){
     Child()
   }
}

期望在某个事件中调用Child的hello()方法,是否可行。这种编程思想是否符合鸿蒙的编程规范,如果不符合,有什么建议能够实现这种效果。

2 回复

可以通过controller来实现,参考这段代码

@Component
struct Child {
  @State private text: string = '初始值'
  private controller: ChildController = new ChildController();

  aboutToAppear() {
    if (this.controller) {
      this.controller.changeText = this.changeText
    }
    console.log('aaa')
  }

  private changeText = (value: string) => {
    this.text = value
    console.log('bbb')
  }

  build() {
    Column() {
      Text(this.text)
    }
  }
}

class ChildController {
  changeText = (value: string) => {
    console.log('11111')
  }
}

export let ChildRef = new ChildController()

@Component
@Entry
struct Parent {
  @State noShow: boolean = false

  build() {
    Column() {
      Text('获取Child的exposeMethods!').fontSize('18vp').fontColor(Color.Gray)
      Divider()
      Child({ controller: ChildRef })
      Child()
      Button('Parent调用childer的changeText').onClick(() => {
        ChildRef.changeText('Parent调用childer的changeText')
      })
    }
  }
}

更多关于HarmonyOS鸿蒙Next中父组件直接调用子组件的方法的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


这句话:export let ChildRef = new ChildController(),应该写在哪个文件呢?我的父子组件不在同一个文件中,

回到顶部