适配版本: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、单例数据、模块共享技巧
将讲解页面与组件之间如何高效共享状态,支持登录状态、主题配置、数据中心等全局状态管理。