Loading、Toast、Dialog 使用与封装:提升用户交互反馈体验 HarmonyOS 5.0.0 或以上

适配版本:HarmonyOS 5.0.0 或以上
阅读目标:掌握用户反馈控件的使用方法,快速集成提示框、加载框与交互弹窗,支持二次封装复用


🧭 一、ArkUI 提供的提示类组件

控件功能说明是否可封装
Toast短时间非阻塞提示
Dialog阻塞式确认/输入交互
Loading加载等待动画

🍞 二、Toast 简易用法(轻提示)

✅ 显示提示:

import prompt from '@system.prompt'

prompt.showToast({
  message: '操作成功',
  duration: 2000
})

✅ 封装通用函数:

export function showToast(msg: string, time: number = 2000) {
  prompt.showToast({ message: msg, duration: time })
}

🔄 三、Loading 显示/隐藏实现(页面级)

@Entry
@Component
struct LoadingExample {
  @State loading: boolean = false

  async simulateRequest() {
    this.loading = true
    await new Promise(resolve => setTimeout(resolve, 1500))
    this.loading = false
    prompt.showToast({ message: '加载完成' })
  }

  build() {
    Column() {
      Button('请求数据')
        .onClick(() => this.simulateRequest())

      if (this.loading) {
        LoadingProgress().margin({ top: 20 })
      }
    }.padding(20)
  }
}

🧩 四、Dialog 对话框使用(确认操作)

import promptAction from '@ohos.promptAction'

function showConfirmDialog() {
  promptAction.showDialog({
    title: '提示',
    message: '你确定要删除吗?',
    buttons: [
      { text: '取消', color: '#999' },
      { text: '确定', color: '#007aff', action: () => console.info('✅ 删除执行') }
    ]
  })
}

🧱 五、封装统一交互模块(如 confirm)

export function confirmDialog(title: string, message: string, onConfirm: () => void) {
  promptAction.showDialog({
    title,
    message,
    buttons: [
      { text: '取消' },
      { text: '确定', color: '#007aff', action: onConfirm }
    ]
  })
}

调用示例:

confirmDialog('提示', '是否退出登录?', () => {
  console.info('🔐 已退出')
})

💡 六、提示组合实战:提交按钮 + 反馈交互

@Entry
@Component
struct SubmitForm {
  @State loading: boolean = false

  async submit() {
    this.loading = true
    await new Promise(resolve => setTimeout(resolve, 1000))
    this.loading = false
    showToast('提交成功!')
  }

  build() {
    Column() {
      Button('提交')
        .onClick(() => this.submit())

      if (this.loading) {
        LoadingProgress().margin({ top: 20 })
      }
    }.padding(20)
  }
}

✅ 七、小结

控件应用场景是否阻塞是否推荐封装
Toast成功/失败等即时反馈
Dialog确认、警告、输入提示
Loading接口请求/上传等等待动作提示

📘 下一篇预告

第27篇|状态管理与全局数据通信方案:Provide/Consume、单例数据、模块共享技巧

将讲解页面与组件之间如何高效共享状态,支持登录状态、主题配置、数据中心等全局状态管理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值