实现弹窗倒计时效果可以参考如下方案进行,其中更新WrappedBuilder对象封装的builder函数参数要用update()方法实现。具体步骤如下:
完整示例参考如下:
import { BusinessError } from '@ohos.base'; import { ComponentContent } from '@ohos.arkui.node'; class Params { text: number = 0; constructor(text: number) { this.text = text; } } @Builder function buildText(params: Params) { Column() { Text(params.text.toString()) .fontSize(50) .fontWeight(FontWeight.Bold) .margin({ bottom: 5, top: 5, right: 5, left: 5 }); }.backgroundColor('#FFF0F0F0'); } @Entry @Component struct TimeIndex { // 使用@State装饰器管理状态,记录动态更新的数值 @State message: number = 10; @State isEnabled: boolean = true; timeout(contentNode: ComponentContent<Params>) { let intervalID = setInterval(() => { contentNode.update(new Params(--this.message)); // 使用update方法更新对话框内容 if (this.message === 0 || this.message < 0) { this.isEnabled = true; clearInterval(intervalID); // 关闭对话框并重置状态 this.getUIContext().getPromptAction().closeCustomDialog(contentNode); this.message = 10; } }, 1000); } build() { Row() { Column() { Button('click me') .enabled(this.isEnabled) .onClick(() => { let uiContext = this.getUIContext(); let promptAction = uiContext.getPromptAction(); // 创建自定义组件内容,包含渲染函数和参数 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); try { this.timeout(contentNode); // 打开自定义对话框 promptAction.openCustomDialog(contentNode, { onWillAppear: () => { this.isEnabled = false; }, onWillDismiss: () => { this.isEnabled = false; }, onDidDisappear: () => { this.message = 10; } }); } catch (error) { let message = (error as BusinessError).message; let code = (error as BusinessError).code; console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`); } }); } .width('100%') .height('100%'); } .height('100%'); } }