鸿蒙自定义弹窗学习总结

1、什么是自定义弹窗?

自定义弹窗的使用更加灵活,适用于更多的业务场景,在自定义弹窗中您可以自定义弹窗内容,构建更加丰富的弹窗界面。自定义弹窗的界面可以通过装饰器@CustomDialog 定义的组件来实现,然后结合 CustomDialogController 来控制自定义弹窗的显示和隐藏。

2、定义自定义弹窗

@CustomDialog
struct CustomDialogExample {
  // 双向绑定传值
  @Prop title: string
  @Link inputValue: string
  // 弹窗控制器,控制打开/关闭,必须传入,且名称必须为:controller
  controller: CustomDialogController
  // 弹窗中的按钮事件
  cancel: () => void
  confirm: () => void
 
  // 弹窗中的内容描述
  build() {
    Column() {
      Text(this.title || "是否修改文本框内容?")
        .fontSize(16)
        .margin(24)
        .textAlign(TextAlign.Start)
        .width("100%")
      TextInput({ 
        placeholder: '文本输入框', 
        text: this.inputValue
      })
        .height(60)
        .width('90%')
        .onChange((value: string) => {
          this.textValue = value
        })
      Flex({ justifyContent: FlexAlign.SpaceAround }) {
        Button('取消')
          .onClick(() => {
            this.controller.close()
            this.cancel()
          }).backgroundColor(0xffffff).fontColor(Color.Black)
        Button('确定')
          .onClick(() => {
            this.controller.close()
            this.confirm()
          }).backgroundColor(0xffffff).fontColor(Color.Red)
      }.margin({ bottom: 10 })
    }
  }
}

3、使用自定义弹窗

@Entry
@Component
struct Index {
  @State title: string = '标题'
  @State inputValue: string = '文本框父子组件数据双绑'
  // 定义自定义弹窗的Controller,传入参数和回调函数
  dialogController: CustomDialogController = new CustomDialogController({
    builder: CustomDialogExample({
      cancel: this.onCancel,
      confirm: this.onAccept,
      textValue: $textValue,
      inputValue: $inputValue
    }),
    cancel: this.existApp,
    autoCancel: true,
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -20 },
    gridCount: 4,
    customStyle: false
  })
 
  aboutToDisappear() {
    this.dialogController = undefined // 将dialogController置空
  }
 
  onCancel() {
    console.info('点击取消按钮', this.inputValue)
  }
 
  onAccept() {
    console.info('点击确认按钮', this.inputValue)
  }
  
  build() {
    Column() {
       Button('打开自定义弹窗')
        .width('60%')
        .margin({top:320})
        .zIndex(999)
        .onClick(()=>{
          if (this.dialogController != undefined) {
            this.dialogController.open()
          }
        })
    }
    .height('100%')
    .width('100%')
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容