React Native (RN)动态权限路由导航(react-navigation)配置
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { createDrawerNavigator } from 'react-navigation-drawer';
import { Platform } from 'react-native';
import { getActiveRouteName } from './pathToActiveRoute';
// 定义导航器的路由配置
const AppNavigator = createStackNavigator({
Home: {
screen: HomeScreen,
navigationOptions: {
title: '主页',
},
},
Profile: {
screen: ProfileScreen,
navigationOptions: {
title: '个人资料',
},
},
// 其他屏幕定义...
});
const DrawerNavigator = createDrawerNavigator({
Home: {
screen: AppNavigator,
navigationOptions: {
drawerLabel: '主页',
drawerIcon: ({ tintColor }) => (
<Icon name="home" size={24} style={{ color: tintColor }} />
),
},
},
Settings: {
screen: SettingsScreen,
navigationOptions: {
drawerLabel: '设置',
drawerIcon: ({ tintColor }) => (
<Icon name="settings" size={24} style={{ color: tintColor }} />
),
},
},
// 其他屏幕定义...
});
// 根据平台选择是否使用 Drawer
const AppContainer = createAppContainer(
Platform.OS === 'ios' ? AppNavigator : DrawerNavigator
);
// 动态权限路由导航配置
export default () => {
const activeRouteName = getActiveRouteName();
return (
<AppContainer
onNavigationStateChange={(prevState, currentState, action) => {
if (action.routeName !== activeRouteName) {
// 根据权限判断是否允许导航
if (!checkPermission(action.routeName)) {
// 没有权限,跳转到登录或者错误页面
AppNavigator.dispatch(AppNavigator.reset({ index: 0, actions: [
AppNavigator.navigate('Login')
]}));
}
}
}}
/>
);
};
这个代码实例展示了如何根据不同的平台选择是否使用 Drawer 导航,并且如何在导航状态变化时进行权限检查,如果不允许访问,则重定向到登录页面或者其他错误页面。这是一个典型的在实际应用中应用的权限路由策略。
评论已关闭