react navigation 任意地方触发导航,不需要 navigation 属性

本文介绍了一种在React Native应用中不使用navigation prop进行导航的方法。通过在顶级导航器上分发导航动作,可以在没有访问到navigation prop的地方触发导航操作。这种方法涉及在App.js中设置一个引用,并将其传递给NavigationService,然后在任何JavaScript模块中调用NavigationService来执行导航。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Navigating without the navigation prop

https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html

Calling functions such as navigate or popToTop on the navigation prop is not the only way to navigate around your app. As an alternative, you can dispatch navigation actions on your top-level navigator, provided you aren't passing your own navigation prop as you would with a redux integration. The presented approach is useful in situations when you want to trigger a navigation action from places where you do not have access to the navigation prop, or if you're looking for an alternative to using the navigation prop.

You can get access to a navigator through a ref and pass it to the NavigationService which we will later use to navigate. Use this only with the top-level (root) navigator of your app.

// App.js

import NavigationService from './NavigationService';

const TopLevelNavigator = createStackNavigator({ /* ... */ })

class App extends React.Component {
  // ...

  render() {
    return (
      <TopLevelNavigator
        ref={navigatorRef => {
          NavigationService.setTopLevelNavigator(navigatorRef);
        }}
      />
    );
  }
}

In the next step, we define NavigationService which is a simple module with functions that dispatch user-defined navigation actions.

// NavigationService.js

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

// add other navigation functions that you need and export them

export default {
  navigate,
  setTopLevelNavigator,
};

Then, in any of your javascript modules, just import the NavigationService and call functions which you exported from it. You may use this approach outside of your React components and, in fact, it works just as well when used from within them.

// any js module
import NavigationService from 'path-to-NavigationService.js';

// ...

NavigationService.navigate('ChatScreen', { userName: 'Lucy' });

In NavigationService, you can create your own navigation actions, or compose multiple navigation actions into one, and then easily reuse them throughout your application. When writing tests, you may mock the navigation functions, and make assertions on whether the correct functions are called, with the correct parameters.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值