概要
自定义弹窗是指在网页或移动应用程序中,用户与应用程序进行交互时弹出的一个窗口。弹窗可以用来展示重要信息、获取用户确认或提供额外的操作选项。与默认的弹窗样式相比,自定义弹窗可以更加灵活、个性化地设计,以满足应用程序的特定需求。
整体架构流程
1.用@CustomDialog装饰器装饰自定义弹框(自定义弹窗的内容)
struct CustomDialogExample {
controller: CustomDialogController
build() {
Column() {
Text('请打开正版原神')
...
}
}
}
2.创建构造器,与装饰器呼应相连
dialogController: CustomDialogController = new CustomDialogController({
builder: CustomDialogExample({
...
}),
})
3.与onClick事件绑定的组件使弹窗弹出
Flex({justifyContent:FlexAlign.Center}){
Button('原神,启动!')
.onClick(() => {
this.dialogController.open()
})
}.width('100%')
4.在@CustomDialog装饰器内添加按钮操作,同时添加数据函数的创建
@Component
@CustomDialog
struct CustomDialogExample {
controller: CustomDialogController
cancel: () => void
confirm: () => void
build() {
Column() {
Text('请打开正版原神').fontSize(20).margin({ top: 10, bottom: 10 })
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 })
}
}
}
5.在构造器内进行接收,同时创建相应的函数操作
@Entry
@Component
struct DialogExample {
dialogController: CustomDialogController = new CustomDialogController({
builder: CustomDialogExample({
cancel: this.onCancel,
confirm: this.onAccept,
}),
alignment: DialogAlignment.Default,
})
onCancel() {
console.info('点击按钮启动!')
}
onAccept() {
console.info('取消启动')
}
build() {
Flex({ justifyContent: FlexAlign.Center }) {
Button('原神,启动!')
.onClick(() => {
this.dialogController.open()
})
}.width('100%')
}
}
整个代码片段以及代码解释
@Component
@CustomDialog //装饰器,用来装饰自定义弹窗
struct CustomDialogExample {
controller: CustomDialogController
cancel: () => void
confirm: () => void // 按键
build() {
Column() {
Text('请打开正版原神').fontSize(20).margin({ top: 10, bottom: 10 })
//用来书写弹窗上的内容
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 })
}
}
}
@Entry
@Component
struct DialogExample {
dialogController: CustomDialogController = new CustomDialogController({ //用来接收上方内容
builder: CustomDialogExample({
cancel: this.onCancel,
confirm: this.onAccept,
}),
alignment: DialogAlignment.Default,
//可设置dialog的对齐方式,设定显示在底部或中间等,默认为底部显示
}) //构造器,与上方装饰器呼应!
onCancel() {
console.info('点击按钮启动!')
}
onAccept() {
console.info('取消启动')
}
build() {
Flex({ justifyContent: FlexAlign.Center }) { //弹窗弹出
Button('原神,启动!')
.onClick(() => {
this.dialogController.open()
})
}.width('100%')
}
}
技术细节
1.注意使用@CustomDialog装饰器装饰自定义弹窗。
2.装饰器和构造器的呼应关系