繁体   English   中英

Ionic 2防止硬件后退按钮默认

[英]Ionic 2 prevent hardware back button default

按下硬件后退按钮时如何防止默认导航? 我尝试过registerBackButtonAction ,但是它覆盖了我不需要的每个页面中后退按钮的行为。

这也没有帮助。

document.addEventListener("backbutton", (event) => {
      event.preventDefault();
  }, false);

如您在Ionic文档中所见, registerBackButtonAction返回一个函数:

该函数在被调用时将取消注册其后退按钮动作。

因此,您可以使用该函数在离开页面时恢复默认行为,如下所示:

import { Component} from '@angular/core';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

    // Property used to store the callback of the event handler to unsubscribe to it when leaving this page
    public unregisterBackButtonAction: any;

    constructor(...) { ... }

    ionViewDidEnter() {
        this.initializeBackButtonCustomHandler();
    }

    ionViewWillLeave() {
        // Unregister the custom back button action for this page
        this.unregisterBackButtonAction && this.unregisterBackButtonAction();
    }

    public initializeBackButtonCustomHandler(): void {
        this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
            this.customHandleBackButton();
        }, 10);
    }

    private customHandleBackButton(): void {
        // do what you need to do here ...
    }
}

如您所见,关键是存储registerBackButtonAction方法的回调,并在以后离开页面时(或要恢复默认行为时)使用它:

this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
    this.customHandleBackButton();
}, 10);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM