HarmonyOS 父组件调用子组件方法

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

父组件调用子组件的方法参考以下代码:

@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()

@Entry
@Component
struct Parent {
  // ChildRef = new ChildController()
  @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')
      })
    }
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
组件调用组件方法
1293浏览 • 1回复 待解决
组件调用组件里的方法
338浏览 • 1回复 待解决
HarmonyOS调用组件方法
454浏览 • 1回复 待解决