1 个回答

在@CustomDialog装饰器中的controller不能用?:的形式声明,并且在组件中使用时,dialogController应该在当前组件下声明,不能在点击事件中声明。如果在事件中声明会导致CustomDialog内子组件的this指不到当前的controller,因此无法关闭弹窗,参考以下代码修改 的组件:

@Entry
@Component
struct CustomDialogUser {
  @Builder mycomp(){
    Button('showtosast')
      .onClick(() => {
        this.dialogController.open()
      })
  }
  dialogController: CustomDialogController = new CustomDialogController({
    builder: CustomDialogExample({
      cancel: ()=> { this.onCancel() },
      confirm: ()=> { this.onAccept() },
    }),
  })

  onCancel() {
    console.info('Callback when the first button is clicked')
  }

  onAccept() {
    console.info('Callback when the second button is clicked')
  }

  build() {
    Column() {
      this.mycomp()
    }.width('100%').margin({ top: 5 })
  }
}

@CustomDialog
struct CustomDialogExample {
  cancel?: () => void
  confirm?: () => void
  controller: CustomDialogController

  build() {
    Column() {
      Text('我是内容').fontSize(20).margin({ top: 10, bottom: 10 })
      Flex({ justifyContent: FlexAlign.SpaceAround }) {
        Button('cancel')
          .onClick(() => {
            this.controller.close()
            if (this.cancel) {
              this.cancel()
            }
          }).backgroundColor(0xffffff).fontColor(Color.Black)
        Button('confirm')
          .onClick(() => {
            this.controller.close()
            if (this.confirm) {
              this.confirm()
            }
          }).backgroundColor(0xffffff).fontColor(Color.Red)
      }.margin({ bottom: 10 })
    }
  }
}

传递builder后this指不到原先的controller,为了避免this指向改变,在TopNavigationView中声明以下代码:

@Builder MenuBuilder() {
  Text('123')
    .width(20)
    .height(20)
    .onClick(() => {
      this.dialogController.open()
    })
}
dialogController: CustomDialogController = new CustomDialogController({
  builder: DescriptionDialog(),
  alignment: DialogAlignment.Center
})

如果在LeaderBoardPage中声明builder,builder中的this指向的是LeaderBoardPage,传递到TopNavigationView后,this指向的是TopNavigationView,但是TopNavigationView中并没有声明dialogController,所以无法关闭弹窗。关于 写死弹窗的问题,弹窗的子组件是 builder: DescriptionDialog(),只需要修改DescriptionDialog组件即可修改弹窗形式,在这个builder中this是指向CustomDialogController的,所以可以打开弹窗。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进