HarmonyOS 弹窗内倒计时刷新UI?

需要动态修改已发送的时间params.mSmsTime,应该如何实现,我的代码如下:

@Builder
function showDialog(params:showDialogParams ){
  Column() {
    Text('已发送('+params.mSmsTime+'秒)').fontSize(16).width(250).height(40).textAlign(TextAlign.Center)
      .onClick(params.send)
  }
}

class showDialogParams {
  send?: () => void = () => {}
  mSmsTime:number=60//获取短信验证码时间
}

let mDialog: ComponentContent<Object> | undefined = undefined;

@Entry
@Component
struct LoginPage {
  @State time:number=60;
  build() {
    Column() {
      Button('click me')
        .onClick(() => {
          if (this.dialogController != null) {
            let uiContext = this.getUIContext();
            let promptAction = uiContext.getPromptAction();

            let params: showDialogParams = {
              autoCancel:false,
              mSmsTime:this.time,
              send:()=>{
                timer=setInterval(()=>{
                  this.time --;

                  if(this.time == 0){
                    this.time = 60;
                    clearInterval(timer)


                    return
                  }
                },1000)
              }
            };
            mDialog=new ComponentContent(uiContext, wrapBuilder(showDialog),params)
            promptAction.openCustomDialog(mDialog)//显示弹窗
          }
        }).backgroundColor(0x317aff)
    }.width('100%').margin({ top: 5 })
  }
}
阅读 553
1 个回答

倒计时建议使用TextTimer组件,参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-texttimer-V5

参考以下demo:

import { promptAction } from '@kit.ArkUI'

@Entry
@Component
struct TextTimerExample {
  private customDialogComponentId: number = 0
  private count: number = 5000
  textTimerController: TextTimerController = new TextTimerController()
  @State format: string = 'ss'
  @State message: string = '获取短信验证码'

  build() {
    Column() {
      Button(this.message)
        .onClick(() => {
          promptAction.openCustomDialog({
            builder: () => {
              this.customDialogComponent()
            }
          }).then((dialogId: number) => {
            this.customDialogComponentId = dialogId
          })
        })
    }
  }

  @Builder customDialogComponent() {
    Column() {
      TextTimer({ isCountDown: true, count: this.count, controller: this.textTimerController })
        .format(this.format)
        .fontColor(Color.Black)
        .fontSize(50)
        .onTimer((utc: number, elapsedTime: number) => {
          console.info('textTimer notCountDown utc is:' + utc + ', elapsedTime: ' + elapsedTime)
          if (elapsedTime == this.count/1000) {
            promptAction.closeCustomDialog(this.customDialogComponentId)
          }
        })
        .onAppear(()=>{
          this.textTimerController.start()
        })
    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进