赞
踩
【问题描述】
在学习ArkTS官方自定义弹窗组件时,想在官方demo(自定义弹窗-弹窗-全局UI方法-组件参考(基于ArkTS的声明式开发范式)-手机、平板、智慧屏和智能穿戴开发-ArkTS API参考-HarmonyOS应用开发)的confirm方法中直接传入修改的值,用一个数组来接收这个值递。伪代码如下:
- @Entry
-
- @Component
-
- struct Demo {
-
- @State inputList: string[] = []
-
- dialogController: CustomDialogController = new CustomDialogController({
-
- builder: CustomDialogWindow({
-
- cancel: this.onCancel,
-
- confirm: this.onConfirm
-
- })
-
- })
-
-
-
- build() {
-
- Column() {
-
- …
-
- Button("OpenDialog").width("60%").onClick(() => {
-
- this.dialogController.open()
-
- })
-
- }.width("100%").height("100%").margin({ top: 20 })
-
- }
-
- …
-
- onConfirm(inputValue: string) {
-
- this.inputList.push(inputValue)
-
- }
-
- }
-
-
-
- @CustomDialog
-
- struct CustomDialogWindow {
-
- controller: CustomDialogController
-
- inputValue: string
-
- cancel: () => void
-
- confirm: (string) => void
-
-
-
- build() {
-
- Column() {
-
- TextInput().width("90%").fontSize(16).onChange(value => this.inputValue = value).margin({ top: 10, bottom: 10 })
-
- Flex({ justifyContent: FlexAlign.SpaceAround }) {
-
- …
-
- Button('确认').onClick(() => {
-
- this.controller.close()
-
- this.confirm(this.inputValue)
-
- }).backgroundColor(0xffffff).fontColor(Color.Red)
-
- }
-
- }
-
- }
-
- }
-

【问题现象】
当在onConfirm方法中想要接收传入的值时,js报错inputList没定义
可是代码明明在Demo中定义了这个数组,并且点击可以跳转,于是通过debug单步调试查看问题到底出在什么地方。
【问题原因】
调试后发现onConfirm方法中的this指向的不是Demo这个struct而是定义的CustomDialog。查阅资料后发现需要在定义dialogController的时候绑定Demo的this给confirm方法才可以正常传值
【修改后】
- @Entry
-
- @Component
-
- struct Demo {
-
- @State inputList: string[] = []
-
- dialogController: CustomDialogController = new CustomDialogController({
-
- builder: CustomDialogWindow({
-
- cancel: this.onCancel,
-
- confirm: this.onConfirm.bind(this)
-
- })
-
- })

这样在onConfirm方法,使用this指针指向的就是Demo,成功解决了问题
欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。