React Navigation:如何根据登录的用户角色从bottomTabNavigator隐藏特定选项卡?

时间:2018-08-21 03:16:47

标签: reactjs react-native react-navigation

我的屏幕上有一个底部标签导航器,具有以下结构(HomeScreen.js):

export default createBottomTabNavigator(
  {
    Home: HomeStack,
    Transactions: TransactionsTab,
    Customers: CustomersStack,
    Settings: SettingsTab
  },
  {
    navigationOptions: ({ navigation }) => ({
      tabBarIcon: ({ focused, tintColor }) => {
        const { routeName } = navigation.state;
        let iconName;
        if (routeName === 'Home') {
          iconName = `home`;
        } else if (routeName === 'Transactions') {
          iconName = `file-text`;
        } else if (routeName === 'Customers') {
          iconName = `users`;
        } else if (routeName === 'Settings') {
          iconName = `settings`;
        }

        return <Feather name={iconName} size={25} color={tintColor} />;
      }
    }),
    tabBarOptions: {
      activeTintColor: '#C62828',
      inactiveTintColor: 'gray',
      style: {
        borderTopWidth: 0,
        elevation: 8,
        backgroundColor: '#FFF'
      }
    }
  }
);

在我的LoginScreen.js中(如果用户已通过身份验证):

resetTo(navigation, 'home');

export function resetTo(navigation, routeName) {
  const resetAction = StackActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({ routeName })]
  });
  navigation.dispatch(resetAction);
}

如果登录的用户无权访问此选项卡,我想隐藏客户选项卡,因此选项卡的数量仅为3。否则为4。在我的登录屏幕上向导航员告诉用户特权,以便导航员可以显示正确的选项卡?

1 个答案:

答案 0 :(得分:0)

如果您也可以向我们提供登录屏幕代码,那么我可以提供更多帮助,根据您的示例代码,您似乎正在使用“反应导航”。在您的登录屏幕上执行此操作

this.props.navigation.navigate('HomeScreen', {loginStatus: status});

然后在构造函数的HomeScreen.js中,您可以像这样读取变量

constructor(props) {
    super(props);
    this.status=props.navigation.getParam('loginStatus');
}

最后,您可以使用此变量现在显示这样的“客户”标签

const test = this.status ? {Home: {screen: MainActivity}} : null;
{
   test,
   Transactions: TransactionsTab,
   Customers: CustomersStack,
   Settings: SettingsTab
}

当然,如果在屏幕之间传递此参数的次数很多,则可以使用诸如Reduce或Reduce-Saga之类的框架,该框架将在整个代码中集中“状态”