React Navigation: How to hide specific tab from bottomTabNavigator based on logged in user role?

此生再无相见时 提交于 2020-01-05 06:33:38

问题


I have a bottom tab navigator in my screen with this structure (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'
      }
    }
  }
);

In my LoginScreen.js (if user is authenticated):

resetTo(navigation, 'home');

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

And I want to hide Customer tab if the logged in user has no privilege to access this tab, so the number of tabs would be only 3. Otherwise, it would be 4. How can I tell the navigator from my login screen about the user privileges so the navigator can show the correct tabs?


回答1:


If you can provide us with your login screen code too I can provide more help, based on your sample code it seems you are using "react-navigation". In your login screen do this

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

Then in your HomeScreen.js in constructor you can read the variable like this

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

and last you can use this variable to now show the customer tab like this

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

Of course if you have many if this parameter passing between your Screens you can use a framework like Redux or Redux-Saga that will centralize your 'state' throughout your code



来源:https://stackoverflow.com/questions/51941099/react-navigation-how-to-hide-specific-tab-from-bottomtabnavigator-based-on-logg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!