0

如何覆盖 onclick 的行为IonBackButton?我能够添加自己的侦听器,但我不知道如何阻止默认侦听器触发。如果他们有未保存的数据,我计划警告用户。

4

4 回答 4

1

从您对我上一篇文章的评论中回复,我不确定我是否理解您真正想要的,但在我看来,只要条件不成立,您就可以为用户禁用后退按钮。并且一旦满足条件,将 disabled 更改为 false。

在 html 中,

<ion-buttons slot="start">
      <ion-back-button disabled="btnCondition"></ion-back-button>
</ion-buttons>

在 .ts 中,

btnCondition:boolean = true; //declare

yourfunction() {
    //Whatever code you want
    if(yourcondition==true){
      btnCondition = false; //This will make the back button to work
    }
    elseif(yourcondition==false) {
      //Do anything
    }
}
于 2020-08-21T09:35:25.063 回答
0

NavContext我使用 in制作了一个自定义后退按钮IonBackButton。这是如何IonBackButton实现的。https://github.com/ionic-team/ionic-framework/blob/main/packages/react/src/components/navigation/IonBackButton.tsx

onClickofIonBackButton的实现如下

(e: React.MouseEvent) => {
    const { defaultHref, routerAnimation } = this.props
    if (this.context.hasIonicRouter()) {
      e.stopPropagation()
      this.context.goBack(defaultHref, routerAnimation)
    } else if (defaultHref !== undefined) {
      window.location.href = defaultHref
    }
  }

这是一个简单的自定义BackButton使用NavContext

import { NavContext } from "@ionic/react"
import React, { useContext } from "react"

interface IBackButtonProps {
  defaultHref?: string
}

export const BackButton: React.FC<IBackButtonProps> = function BackButton({
  defaultHref = "/",
}) {
  const navContext = useContext(NavContext)
  const onClick = (e: React.MouseEvent) => {
    if (navContext.hasIonicRouter()) {
      e.stopPropagation()
      navContext.goBack(defaultHref, undefined)
    } else if (defaultHref !== undefined) {
      window.location.href = defaultHref
    }
  }

  return <button onClick={onClick} style={{ width: 48, height: 48 }} />
}

确保可能存在一些意外行为,因为上述组件仅实现onClick事件。它不使用IonBackButtonInnerwhich 是IonBackButton.

于 2022-01-10T05:28:00.163 回答
0

如果你使用 ionic 4/5,你可以这样设置,

<ion-buttons slot="start">
      <ion-back-button defaultHref="home"></ion-back-button>
</ion-buttons>

如果它不起作用,您还可以使用 ion-icon 和 put click 功能导航到其他页面。

于 2020-08-18T01:46:59.553 回答
0

您还可以覆盖后退按钮的订阅,例如在 app.component.ts

  private backButtonEvent() {
    this.platform.backButton.subscribeWithPriority(1, () => {
      console.log('BACK BUTTON TRIGGERED');
      this.yourFunction();
    });
  }

如果您只想阻止当前 ts 文件中的任何操作:

ionViewWillEnter() {
    this.backButtonSubscription = this.platform.backButton.subscribeWithPriority(9999, () => {});
  }

ionViewWillLeave() {
  this.backButtonSubscription.unsubscribe();
}
于 2022-01-10T12:10:51.120 回答