【问题标题】:How to trigger redirect with back direction in Ionic React 5?如何在 Ionic React 5 中触发反向重定向?
【发布时间】:2020-06-22 06:00:46
【问题描述】:

如何在Ionic router 中触发重定向到具有给定动画方向(例如返回)的给定位置,而无需单击路由器链接元素?

有一种触发路由器重定向的标准方法。问题是它不能改变动画方向所以它总是向前的:

// history is a value from react-router, it can be obtained from the HOC of the hook
history.push('/new/address');

还有一种方法可以返回,但是不能设置自定义URL去:

history.goBack();

我也可以制作一个按钮并触发点击它,但它看起来像一个笨拙的解决方案:

const buttonRef = useRef();

const redirect = () => buttonRef.current.click();

return (
  <IonButton
    routerLink="/new/address"
    routerDirection="back"
    ref={buttonRef}
    style={{display: 'none'}}
  />
);

【问题讨论】:

    标签: javascript reactjs ionic-framework ionic5


    【解决方案1】:

    有一种未记录的方法可以触发 Ionic 路由器重定向到具有任何动画的任何地址:NavContext。它只能在 React 组件中使用。

    import React, {Component, useCallback, useContext} from 'react';
    import {NavContext} from '@ionic/react';
    
    // Functional component example
    function MyComponent() {
      const {navigate} = useContext(NavContext);
    
      // Call this function when required to redirect with the back animation
      const redirect = useCallback(
        () => navigate('/new/address', 'back'),
        [navigate]
      );
    }
    
    // Class component example
    class MyComponent extends Component {
      static contextType = NavContext;
    
      // Call this method when required to redirect with the back animation
      redirect() {
        this.context.navigate('/new/address', 'back');
      }
    }
    

    第二个参数的可能值与 Ionic 链接组件中的相同:backforwardroot

    【讨论】:

    • 在 iOS 上不适用于我。我应该以某种方式更新它吗?
    • @PawełStanecki 当我发布这个答案时,它在每个平台上都有效。可能是 Ionic 更改了 API,或者您的代码中有错误。
    【解决方案2】:

    正如@Finesse 指出的那样,Ionic 的反应库提供了NavContext 导航上下文,它在双关语的导航上下文中公开了几个有用的方法。

    其中有 goBack() 方法,它只是导航回来。它需要一个默认路由导航到。我想这是针对后堆栈上没有先前项目的情况。可以这样使用:

    import {useContext} from 'react'
    import {NavContext} from '@ionic/react'
    ...
    const {goBack} = useContext(NavContext)
    goBack('/alternative/path/if/empty/history')
    ...
    

    除了navigate()goBack(),上下文还提供以下字段:

    export interface NavContextState {
      getPageManager: () => any;
      getStackManager: () => any;
      goBack: (defaultHref?: string) => void;
      navigate: (path: string, direction?: RouterDirection | 'none', ionRouteAction?: 'push' | 'replace' | 'pop') => void;
      hasIonicRouter: () => boolean;
      registerIonPage: (page: HTMLElement) => void;
      currentPath: string | undefined;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2018-03-22
      • 2016-12-12
      • 2020-09-16
      • 1970-01-01
      • 2015-08-06
      • 2022-01-20
      相关资源
      最近更新 更多