当前位置:   article > 正文

【ArkTS】ArkTS开发组件回调中this指向问题_arkts this

arkts this

【问题描述】

在学习ArkTS官方自定义弹窗组件时,想在官方demo(自定义弹窗-弹窗-全局UI方法-组件参考(基于ArkTS的声明式开发范式)-手机、平板、智慧屏和智能穿戴开发-ArkTS API参考-HarmonyOS应用开发)的confirm方法中直接传入修改的值,用一个数组来接收这个值递。伪代码如下:

  1. @Entry
  2. @Component
  3. struct Demo {
  4. @State inputList: string[] = []
  5. dialogController: CustomDialogController = new CustomDialogController({
  6. builder: CustomDialogWindow({
  7. cancel: this.onCancel,
  8. confirm: this.onConfirm
  9. })
  10. })
  11. build() {
  12. Column() {
  13. Button("OpenDialog").width("60%").onClick(() => {
  14. this.dialogController.open()
  15. })
  16. }.width("100%").height("100%").margin({ top: 20 })
  17. }
  18. onConfirm(inputValue: string) {
  19. this.inputList.push(inputValue)
  20. }
  21. }
  22. @CustomDialog
  23. struct CustomDialogWindow {
  24. controller: CustomDialogController
  25. inputValue: string
  26. cancel: () => void
  27. confirm: (string) => void
  28. build() {
  29. Column() {
  30. TextInput().width("90%").fontSize(16).onChange(value => this.inputValue = value).margin({ top: 10, bottom: 10 })
  31. Flex({ justifyContent: FlexAlign.SpaceAround }) {
  32. Button('确认').onClick(() => {
  33. this.controller.close()
  34. this.confirm(this.inputValue)
  35. }).backgroundColor(0xffffff).fontColor(Color.Red)
  36. }
  37. }
  38. }
  39. }

【问题现象】

当在onConfirm方法中想要接收传入的值时,js报错inputList没定义

cke_1096.png

可是代码明明在Demo中定义了这个数组,并且点击可以跳转,于是通过debug单步调试查看问题到底出在什么地方。

【问题原因】

调试后发现onConfirm方法中的this指向的不是Demo这个struct而是定义的CustomDialog。查阅资料后发现需要在定义dialogController的时候绑定Demo的this给confirm方法才可以正常传值

【修改后】

  1. @Entry
  2. @Component
  3. struct Demo {
  4. @State inputList: string[] = []
  5. dialogController: CustomDialogController = new CustomDialogController({
  6. builder: CustomDialogWindow({
  7. cancel: this.onCancel,
  8. confirm: this.onConfirm.bind(this)
  9. })
  10. })

这样在onConfirm方法,使用this指针指向的就是Demo,成功解决了问题

欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/292529
推荐阅读
相关标签
  

闽ICP备14008679号