如何解决如何从 Ionic5 代码触发后退按钮
我需要触发相同的功能,导航菜单中的后退按钮将通过代码触发。
<ion-buttons slot="start">
<ion-back-button></ion-back-button>
</ion-buttons>
我正在使用
this.router.navigate(['/previousPage',{
demoMode: false
}]);
但是在开始视图上与 D3 存在奇怪的不一致,后退按钮不会发生,但 router
会发生。我只是不知道后退按钮在后台触发了哪个功能。猜猜它一定是类似于 navCtrl.pop
?
解决方法
了解这些事情的最好方法是查看 Ionic 的源代码。 Ionic 的源代码组织得非常好,所以大多数时候很容易找到某些组件在幕后做了什么。
关于您的问题,this is the code of the ion-back-button directive。
基于此,似乎 Ionic 使用 IonRouterOutlet
(如果可用)或 NavController
否则:
if (this.routerOutlet && this.routerOutlet.canGoBack()) {
this.navCtrl.setDirection('back',undefined,this.routerAnimation);
this.routerOutlet.pop();
// ...
} else if (defaultHref != null) {
this.navCtrl.navigateBack(defaultHref,{ animation: this.routerAnimation });
}
知道了这一点,您就可以编写一个完全相同的方法。请查看this Stackblitz demo。
代码中最相关的部分是DetailsPage
:
import { Component,Optional } from "@angular/core";
import { IonRouterOutlet,NavController } from "@ionic/angular";
@Component({
selector: "app-details",templateUrl: "./details.page.html",styleUrls: ["./details.page.scss"]
})
export class DetailsPage {
constructor(
@Optional() private routerOutlet: IonRouterOutlet,private navCtrl: NavController
) {}
public goBack(): void {
if (this.routerOutlet && this.routerOutlet.canGoBack()) {
this.navCtrl.setDirection("back");
this.routerOutlet.pop();
} else {
this.navCtrl.navigateBack("/home");
}
}
}
在演示中我省略了设置自定义页面转换,但如果您在应用中使用自定义页面转换,则可以这样做。
顺便说一句,如果您想简化该代码,我想您可以直接使用 this.navCtrl.navigateBack("/home");
,因为 Ionic 5 中的 NavController
在幕后使用了 Angular 的路由器(可以看出 {{ 3}}).
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。