页面A跳转到页面B,页面B使用UIContext.getPromptAction().openCustomDialog()的方式弹出自定义弹框,此时页面B返回到页面A,但弹框未消失。
需要实现的效果是弹框能在B页面退出后自动跟随消失,即弹窗跟随页面一起消失。
创建DialogOne并实现跳转到DialogTwo,使用弹窗组件的onWillDismiss()回调函数对应的枚举值实现关闭弹窗。并跳转回Dialog1页面。同时也可以实现侧滑返回页面A时,页面B与弹窗一起消失。
@Entry
@Component
struct DialogOne {
pageInfo: NavPathStack = new NavPathStack();
build() {
Navigation(this.pageInfo) {
Column() {
Button('点击跳转')
.id('Dialog1HelloWorld')
.backgroundColor('#0a59f7')
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.pageInfo.pushPath({ name: 'DialogTwo' });
});
}
.justifyContent(FlexAlign.Center)
.padding(16)
.height('100%')
.width('100%');
};
}
} @Builder
export function DialogTwoBuilder() {
DialogTwo();
}
@Component
export struct DialogTwo {
private customDialogComponentId: number = 0;
pageInfo: NavPathStack = new NavPathStack();
ctx: UIContext = this.getUIContext();
@Builder
customDialogComponent() {
Column() {
Text('弹窗')
.fontSize(24)
.fontWeight(FontWeight.Bold);
Text('点击确定返回DialogOne并关闭弹窗');
Row() {
Button('取消')
.width('45%')
.borderRadius(20)
.backgroundColor(Color.Transparent)
.fontColor('#0a59f7')
.onClick(() => {
try {
this.ctx.getPromptAction().closeCustomDialog(this.customDialogComponentId);
} catch (error) {
console.error(error);
}
});
Button('确认')
.width('45%')
.borderRadius(20)
.onClick(() => {
// 模拟B页面操作返回
this.pageInfo.pop();
});
}
.width('100%')
.justifyContent(FlexAlign.SpaceAround);
}
.height(200)
.padding(16)
.justifyContent(FlexAlign.SpaceEvenly);
}
build() {
NavDestination() {
Column({ space: 16 }) {
Button('点击返回')
.onClick(() => {
this.ctx.getPromptAction().openCustomDialog({
builder: () => {
this.customDialogComponent();
},
onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
console.info(`reason: ${JSON.stringify(dismissDialogAction.reason)}`);
console.info('dialog onWillDismiss');
if (dismissDialogAction.reason === DismissReason.PRESS_BACK) {
this.pageInfo.pop();
}
}
}).then((dialogId: number) => {
this.customDialogComponentId = dialogId;
});
});
}
.onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
this.ctx.getPromptAction().closeCustomDialog(this.customDialogComponentId);
console.info(`isVisible: ${isVisible}, currentRatio: ${currentRatio}`);
})
.padding(16)
.height('100%');
}
.hideTitleBar(true)
.onReady((value) => {
this.pageInfo = value.pathStack;
});
}
} {
"routerMap": [
{
"name" : "DialogTwo",
"pageSourceFile" : "src/main/ets/pages/DialogTwo.ets",
"buildFunction" : "DialogTwoBuilder"
}
]
}