介绍
CustomDialog 是实现 高度定制化弹窗 的核心组件,它允许开发者完全控制弹窗的 布局、样式、交互逻辑及数据绑定
特点
布局自由:支持任意UI组件组合(如文本、输入框、按钮、图片、列表等),可构建复杂表单、多步骤向导或动态内容弹窗。
样式定制:通过CSS属性(如背景色、边框、阴影、圆角)和动画效果(如淡入淡出、缩放、滑动)实现品牌风格统一。
交互逻辑:可自定义按钮行为、输入验证、拖拽关闭、键盘适配等交互细节。
方法
通过构造方法定制
constructor(value: CustomDialogControllerOptions)
参数:
- value:
CustomDialogControllerOptions类型
open()
显示自定义弹窗
close()
关闭显示的自定义弹窗,若已关闭,则不生效
CustomDialogControllerOptions
builder:CustomDialog类型,必填,自定义弹窗内容构造器。
cancel:
() => void,非必填,返回、ESC键和点击遮障层弹窗退出时的回调。
CustomDialogController
CustomDialogController 仅在作为 @CustomDialog 和 @Component struct 的成员变量,且在 @Component struct 内部定义时赋值才有效,具体用法可看下方示例。
dialogController : CustomDialogController
例子:输入对话框
注意:可能预览模式不能运行,需要在模拟器下运行
在 @Entry 上方加上下面代码:
@CustomDialog
struct InputDialog {
@State name: string = '';
controller: CustomDialogController;
cancel?: () => void;
confirm?: (name: string) => void;
build() {
Column({ space: 20 }) {
Text('请输入姓名')
.fontSize(20)
.fontWeight(FontWeight.Bold);
TextInput({ placeholder: '姓名' })
.width('90%')
.margin({ top: 10, bottom: 10 })
.onChange((value: string) => this.name = value)
Row() {
Button('取消')
.onClick(() => {
this.controller.close();
this.cancel?.();
});
Button('确认')
.backgroundColor(Color.Blue)
.onClick(() => {
this.controller.close();
this.confirm?.(this.name);
});
}
}
.padding(20)
}
}
在 struct Index{} 中定义下面变量:
@State userName: string = '';
dialogController: CustomDialogController = new CustomDialogController({
builder: InputDialog({
cancel: () => console.log('取消输入'),
confirm: (name: string) => {
this.userName = name;
console.log("姓名:",name)
}
}),
alignment: DialogAlignment.Center, // 弹窗居中
autoCancel: true // 点击外部关闭
});
加上下面按钮,点击按钮弹出对话框:
Button('输入姓名')
.width('80%')
.margin(20)
.onClick(() => this.dialogController.open());