Fin*_*sse 4 javascript reactjs ionic-framework ionic5
如何在不单击路由器链接元素的情况下在Ionic 路由器中以给定的动画方向(例如,返回)触发重定向到给定位置?
有一种标准方法可以触发路由器重定向。问题是它不能改变动画方向,所以它总是向前:
// history is a value from react-router, it can be obtained from the HOC of the hook
history.push('/new/address');
Run Code Online (Sandbox Code Playgroud)
还有一个方法可以返回,但是不能设置自定义URL去:
history.goBack();
Run Code Online (Sandbox Code Playgroud)
我也可以制作一个按钮并触发点击它,但它看起来像一个笨拙的解决方案:
const buttonRef = useRef();
const redirect = () => buttonRef.current.click();
return (
<IonButton
routerLink="/new/address"
routerDirection="back"
ref={buttonRef}
style={{display: 'none'}}
/>
);
Run Code Online (Sandbox Code Playgroud)
Fin*_*sse 12
有触发离子路由器重定向到任何动画任何地址的无证方法: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');
}
}
Run Code Online (Sandbox Code Playgroud)
第二个参数的可能值与 Ionic 链接组件中的相同:back、forward和root。
正如@Finesse 指出的那样,Ionic 的 react 库提供了NavContext导航上下文,它在导航上下文中公开了一些有用的方法。
其中包括goBack()简单地导航回去的方法。它需要一个默认路由来导航。我想这适用于后堆栈中没有先前项目的情况。它可以按如下方式使用:
import {useContext} from 'react'
import {NavContext} from '@ionic/react'
...
const {goBack} = useContext(NavContext)
goBack('/alternative/path/if/empty/history')
...
Run Code Online (Sandbox Code Playgroud)
此外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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2669 次 |
| 最近记录: |