当前不支持将弹窗代码分离到类中,可以将不同弹窗的UI样式与函数封装到自定义组件中,通过自定义组件调用灵活复用弹窗功能。参考demo如下:@Entry @Component struct Index8 { @State message: string = 'Hello World'; @State ifOpen: boolean = false; build() { Column() { Button('打开弹窗').onClick(() => { this.ifOpen = true }) CustomDialogChild({ //控制弹窗内容展示 textValue: '测试在别的页面传参并打开弹窗', isOpen: this.ifOpen, //控制弹窗UI样式渲染 param: '1' }) } .justifyContent(FlexAlign.Center) .height('100%') .width('100%') } } /** * 将UI样式封装在自定义组件中,并通过@BuilderParam传递给具体弹窗 */ @Component export struct CustomDialogChild { @Prop textValue: string = '' @State inputValue: string = 'click me' @Link @Watch('onStateChange') isOpen: boolean; @State param: string = '1' /** * 构建UI样式 */ @Builder setUI() { Text('这是一个UI') } dialogController: CustomDialogController | null = new CustomDialogController({ builder: CustomDialogExample({ cancel: () => { this.onCancel() }, confirm: () => { this.onAccept() }, getUI: () => { //控制不同样式的UI渲染 if (this.param === '1') { this.setUI() } else { } }, textValue: $textValue, inputValue: $inputValue, isOpen: $isOpen }), cancel: this.exitApp, autoCancel: false, alignment: DialogAlignment.Bottom, offset: { dx: 0, dy: -20 }, gridCount: 4, customStyle: false, cornerRadius: 10, }) onStateChange() { if (this.isOpen) { this.dialogController?.open() } else { this.dialogController?.close(); } } // 在自定义组件即将析构销毁时将dialogControlle置空 aboutToDisappear() { this.dialogController = null // 将dialogController置空 } onCancel() { console.info('Callback when the first button is clicked') } onAccept() { console.info('Callback when the second button is clicked') } exitApp() { console.info('Click the callback in the blank area') } build() { } } @CustomDialog struct CustomDialogExample { @Link textValue: string @Link inputValue: string; @Link isOpen: boolean; @BuilderParam getUI: () => void controller?: CustomDialogController // 若尝试在CustomDialog中传入多个其他的Controller,以实现在CustomDialog中打开另一个或另一些CustomDialog,那么此处需要将指向自己的controller放在所有controller的后面 cancel: () => void = () => { } confirm: () => void = () => { } build() { Column() { Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 }) TextInput({ placeholder: '', text: this.textValue }).height(60).width('90%') .onChange((value: string) => { this.textValue = value }) Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 }) Flex({ justifyContent: FlexAlign.SpaceAround }) { Button('cancel') .onClick(() => { if (this.controller != undefined) { this.controller.close() this.cancel(); this.isOpen = false; } }).backgroundColor(0xffffff).fontColor(Color.Black) Button('confirm') .onClick(() => { if (this.controller != undefined) { this.inputValue = this.textValue this.controller.close() this.isOpen = false; this.confirm() } }).backgroundColor(0xffffff).fontColor(Color.Red) }.margin({ bottom: 10 }) this.getUI() }.borderRadius(10) // 如果需要使用border属性或cornerRadius属性,请和borderRadius属性一起使用。 } }
当前不支持将弹窗代码分离到类中,可以将不同弹窗的UI样式与函数封装到自定义组件中,通过自定义组件调用灵活复用弹窗功能。
参考demo如下: