#跟着晓明学鸿蒙# HarmonyOS Stack组件实现对话框交互功能
·

案例介绍
本教程将介绍如何实现自定义对话框的交互功能。我们将为对话框添加显示、隐藏、确认、取消等交互操作,并实现输入验证和结果反馈功能。
代码实现
@Entry
@Component
struct CustomDialogExample {
@State showInfoDialog: boolean = false
@State showConfirmDialog: boolean = false
@State showInputDialog: boolean = false
@State inputValue: string = ''
@State resultMessage: string = ''
build() {
Stack() {
Column() {
// 按钮区域
Column({ space: 16 }) {
Button('显示信息对话框')
.width('100%')
.height(50)
.onClick(() => {
this.showInfoDialog = true
})
Button('显示确认对话框')
.width('100%')
.height(50)
.onClick(() => {
this.showConfirmDialog = true
})
Button('显示输入对话框')
.width('100%')
.height(50)
.onClick(() => {
this.inputValue = ''
this.showInputDialog = true
})
}
}
// 对话框显示控制
if (this.showInfoDialog) {
this.InfoDialog()
}
if (this.showConfirmDialog) {
this.ConfirmDialog()
}
if (this.showInputDialog) {
this.InputDialog()
}
}
}
// 信息对话框构建器
@Builder
InfoDialog() {
Column()
.width('100%')
.height('100%')
.backgroundColor('#00000080')
.onClick(() => {
this.showInfoDialog = false
})
Column() {
Button('确定')
.width('100%')
.height(40)
.onClick(() => {
this.showInfoDialog = false
this.resultMessage = '您关闭了信息对话框'
})
}
.onClick((event) => {
event.stopPropagation()
})
}
// 确认对话框构建器
@Builder
ConfirmDialog() {
Column()
.backgroundColor('#00000080')
.onClick(() => {
this.showConfirmDialog = false
})
Column() {
Row({ space: 16 }) {
Button('取消')
.onClick(() => {
this.showConfirmDialog = false
this.resultMessage = '您取消了操作'
})
Button('确认')
.onClick(() => {
this.showConfirmDialog = false
this.resultMessage = '您确认了操作'
})
}
}
.onClick((event) => {
event.stopPropagation()
})
}
// 输入对话框构建器
@Builder
InputDialog() {
Column()
.backgroundColor('#00000080')
.onClick(() => {
this.showInputDialog = false
})
Column() {
TextInput({ placeholder: '请在此输入...', text: this.inputValue })
.onChange((value) => {
this.inputValue = value
})
Row({ space: 16 }) {
Button('取消')
.onClick(() => {
this.showInputDialog = false
})
Button('提交')
.onClick(() => {
if (this.inputValue.trim() === '') {
this.resultMessage = '输入内容不能为空'
return
}
this.showInputDialog = false
this.resultMessage = `您输入的内容是:${this.inputValue}`
})
}
}
.onClick((event) => {
event.stopPropagation()
})
}
}
代码详解
交互事件处理
-
对话框显示控制
- 点击按钮时设置对应的显示状态为true
- 使用条件渲染控制对话框的显示和隐藏
- 每个对话框都有独立的显示状态变量
-
点击事件处理
- 背景点击关闭对话框
- 内容区域阻止事件冒泡
- 按钮点击执行相应的操作
-
输入处理
- 输入框onChange事件更新inputValue
- 提交时验证输入内容
- 输入为空时显示错误提示
功能实现
-
信息对话框
- 单个确定按钮
- 点击确定关闭对话框
- 更新操作结果消息
-
确认对话框
- 取消和确认两个按钮
- 不同按钮产生不同的结果消息
- 点击任意按钮关闭对话框
-
输入对话框
- 包含输入框和按钮组
- 实时更新输入内容
- 提交时进行输入验证
事件传播控制
-
背景点击
- 点击半透明背景关闭对话框
- 实现点击外部区域关闭的交互模式
-
内容区域点击
- 使用stopPropagation阻止事件冒泡
- 防止点击内容区域时触发背景点击事件
-
按钮点击
- 独立的onClick事件处理器
- 执行特定的业务逻辑
- 更新状态和结果消息
总结
通过合理的事件处理和状态管理,我们实现了功能完整的对话框交互系统。每种类型的对话框都有其特定的交互逻辑,同时共享一些通用的交互模式,如点击外部关闭、事件冒泡控制等。这种实现方式既保证了良好的用户体验,又维护了代码的可维护性。
更多推荐


所有评论(0)