弹窗是一种模态窗口,通常用来展示用户当前需要的或用户必须关注的信息或操作。在弹出框消失之前,用户无法操作其他界面内容。ArkUI 为我们提供了丰富的弹窗功能,弹窗按照功能可以分为以下两类:
- 确认类:例如警告弹窗 AlertDialog。
- 选择类:包括文本选择弹窗 TextPickerDialog 、日期滑动选择弹窗 DatePickerDialog、时间滑动选择弹窗 TimePickerDialog 等。
可以根据业务场景,选择不同类型的弹窗。
1、什么是自定义弹窗?
自定义弹窗的使用更加灵活,适用于更多的业务场景,在自定义弹窗中您可以自定义弹窗内容,构建更加丰富的弹窗界面。自定义弹窗的界面可以通过装饰器@CustomDialog 定义的组件来实现,然后结合 CustomDialogController 来控制自定义弹窗的显示和隐藏。
2、定义自定义弹窗
@CustomDialog
struct CustomDialogExample {
// 双向绑定传值
@Prop title: string
@Link inputValue: string
// 弹窗控制器,控制打开/关闭,必须传入,且名称必须为:controller
controller: CustomDialogController
// 弹窗中的按钮事件
cancel: () => void
confirm: () => void
// 弹窗中的内容描述
build() {
Column() {
Text(this.title || "是否修改文本框内容?")
.fontSize(16)
.margin(24)
.textAlign(TextAlign.Start)
.width("100%")
TextInput({
placeholder: '文本输入框',
text: this.inputValue
})
.height(60)
.width('90%')
.onChange((value: string) => {
this.textValue = value
})
Flex({ justifyContent: FlexAlign.SpaceAround }) {
Button('取消')
.onClick(() => {
this.controller.close()
this.cancel()
}).backgroundColor(0xffffff).fontColor(Color.Black)
Button('确定')
.onClick(() => {
this.controller.close()
this.confirm()
}).backgroundColor(0xffffff).fontColor(Color.Red)
}.margin({ bottom: 10 })
}
}
}
3、使用自定义弹窗
@Entry
@Component
struct Index {
@State title: string = '标题'
@State inputValue: string = '文本框父子组件数据双绑'
// 定义自定义弹窗的Controller,传入参数和回调函数
dialogController: CustomDialogController = new CustomDialogController({
builder: CustomDialogExample({
cancel: this.onCancel,
confirm: this.onAccept,