路由器(Routers)

路由器定义了一个组件的导航状态,并允许开发人员定义可被处理的路径和动作。

内置路由器(Built-In Routers)

react-navigation使用的几个标准的路由器:

使用路由器(Using Routers)

要手动导航,请在组件上放置一个静态路由器。(要快速创建一个使用内置组件的导航器,使用一个 Navigator Factory 将其取代可能会更容易)

1
2
3
4
class MyNavigator extends React.Component {
static router = StackRouter(routes, config);
...
}

现在您可以将此组件用作另一个导航器中的屏幕,而MyNavigator的导航逻辑将由此StackRouter定义。

自定义路由器(Customizing Routers)

请参阅自定义路由器API规范了解StackRouterTabRouter的API。您可以根据需要覆盖路由器的功能:

自定义导航动作(Custom Navigation Actions)

要覆盖导航行为,您可以覆盖getStateForAction中的导航状态逻辑,并手动操作 routesindex

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const MyApp = StackNavigator({
Home: { screen: HomeScreen },
Profile: { screen: ProfileScreen },
}, {
initialRouteName: 'Home',
})

const defaultGetStateForAction = MyApp.router.getStateForAction;

MyApp.router.getStateForAction = (action, state) => {
if (state && action.type === 'PushTwoProfiles') {
const routes = [
...state.routes,
{key: 'A', routeName: 'Profile', params: { name: action.name1 }},
{key: 'B', routeName: 'Profile', params: { name: action.name2 }},
];
return {
...state,
routes,
index: routes.length - 1,
};
}
return defaultGetStateForAction(action, state);
};

阻止导航操作(Blocking Navigation Actions)

有时您可能希望防止某些导航活动,具体取决于您的路由。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const MyStackRouter = StackRouter({
Home: { screen: HomeScreen },
Profile: { screen: ProfileScreen },
}, {
initialRouteName: 'Home',
})

const defaultGetStateForAction = MyStackRouter.router.getStateForAction;

MyStackRouter.router.getStateForAction = (action, state) => {
if (
state &&
action.type === NavigationActions.BACK &&
state.routes[state.index].params.isEditing
) {
// 从getStateForAction返回null表示操作已被处理/阻止,但没有新的状态
return null;
}

return defaultGetStateForAction(action, state);
};

处理自定义URI(Handling Custom URIs)

也许您的应用程序具有内置路由器无法处理的唯一URI. 您可以随时扩展路由器的getActionForPathAndParams

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

import { NavigationActions } from 'react-navigation'

const MyApp = StackNavigator({
Home: { screen: HomeScreen },
Profile: { screen: ProfileScreen },
}, {
initialRouteName: 'Home',
})
const previousGetActionForPathAndParams = MyApp.router.getActionForPathAndParams;

Object.assign(MyApp.router, {
getActionForPathAndParams(path, params) {
if (path === 'my/custom/path' && params.magic === 'yes') {
//返回一个profile导航操作 /my/custom/path?magic=yes
return NavigationActions.navigate({
routeName: 'Profile',
action: NavigationActions.navigate({
//该子操作将被传递给子路由器ProfileScreen.router.getStateForAction以获取子导航状态。
routeName: 'Friends',
}),
});
}
return previousGetActionForPathAndParams(path, params);
},
});
感谢您的支持,这将鼓励我坚持技术分享!