HarmonyOS 状态管理V2如何在ComponentV2修饰的组件中使用自定义对话框并且向对话框的builder传值?

ComponentV2修饰的组件中,使用对话框,如何向自定义对话框builder传值?如何双向绑定变量?

自定义对话框builder好像只能使用V1的状态管理?该如何使用V2的状态管理呢?

如图1所示自定义对话框的Builder

如图2所示在ComponentV2的组件中使用这个builder,并且传入了@Local dialogMessage变量。

如图3所示在ComponentV2的组件中一直修改this.dialogMessage变量,对话框的值并不更新。

请问如何正确在ComponentV2中使用自定义对话框?

阅读 486
1 个回答

当前@CustomDialog无法使用@ComponentV2的修饰器,建议使用参考下面方式使用弹窗

import { HMRouter } from '@dssuite/hmrouter';
import { ComponentContent } from '@kit.ArkUI';

let contentNode: ComponentContent<MyCustomDialog>

interface DialogParams {
  visible: boolean
  onCancel?: () => void;
  onConfirm?: () => void;
}


@Builder
function buildBackConfirmDialog(dialogParams: DialogParams) {
  MyCustomDialog({ visible: dialogParams.visible, onCancel: dialogParams.onCancel, onConfirm: dialogParams.onConfirm })
}

@HMRouter({ pageUrl: "240828162414031" })
@ComponentV2
export struct IR240828162414031 {
  @Local visible: boolean = false
  @Local openDialogCount: number = 0;
  @Local cancelDialogCount: number = 0;

  @Monitor('visible')
  visibleOnChange() {
    if (this.visible) {
      this.getUIContext().getPromptAction().openCustomDialog(contentNode, {
        onWillDismiss: (data) => {
        }
      })
    } else {
      this.getUIContext().getPromptAction().closeCustomDialog(contentNode)
    }
  }

  aboutToAppear(): void {
    contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildBackConfirmDialog),
      {
        visible: this.visible,
        onCancel: () => {
          this.cancelDialogCount++
          this.visible = false
        },
        onConfirm: () => {
          this.openDialogCount++
          this.visible = false
        }
      } as DialogParams)
  }

  build() {
    Column({ space: 20 }) {
      Text(`open dialog count: ${this.openDialogCount}`)
        .fontSize(20)
      Text(`cancel dialog count: ${this.cancelDialogCount}`)
        .fontSize(20)
      Button(this.visible ? 'hide' : 'show')// 点击修改visible变量后,visible的值可以被Dialog组件监听并响应
        .onClick(() => this.visible = !this.visible)
    }
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }
}


@ComponentV2
struct MyCustomDialog {
  @Param visible: boolean = false;
  // 弹窗交互事件参数,点击确认和取消按钮时的回调函数
  @Param onCancel?: () => void | undefined = undefined;
  @Param onConfirm?: () => void | undefined = undefined;

  build() {
    Column({ space: 12 }) {
      Text("Custom dialog content!")
        .fontSize(20)
      Row() {
        Button("cancel")
          .onClick(() => {
            this.onCancel?.();
          })
          .margin({ right: 20 })
        Button("confirm")
          .onClick(() => {
            this.onConfirm?.();
          })
      }
      .justifyContent(FlexAlign.Center)
    }
    .padding(24)
    .backgroundColor(Color.White)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进