问题
I'm developing a react-native app with a bottom-tab-navigator, and would like navigation options to depend on the screen being displayed, something like:
AppNavigator.js:
class AppNavigator extends React.Component{
isRouteEnabled = (routeName) => {
return this.props.route == routeName;
}
render() {
const tabNavigator = createBottomTabNavigator({
Home: HomeScreen,
Screen2: Screen2,
// tab to be conditionally displayed
...(this.isRouteEnabled('Screen3') ? { Screen3 : Screen3} : {})
});
const AppNavigator = createAppContainer(tabNavigator);
return <AppNavigator />
}
}
The problem I'm having is accessing this.props within this class, currently it's always undefined. If possible I'd like it to use values from my redux store, however if I wrap AppNavigator in a connect() call making it a higher-level component navigation no longer works at all (for reasons I don't understand):
const mapStateToProps = (state) => ({ route: state.route })
export default connect(mapStateToProps)(AppNavigator);
App.js is straightforward:
export default class App extends React.Component {
render() {
return (
<Provider store={appStore}>
<AppNavigator />
</Provider>
);
}
}
Am I missing something - is it possible to have a navigator with dynamic behavior that depends on values stored in redux?
回答1:
Current version of React Navigation has a static configuration API, which means all configuration must be done outside render. This makes use cases such as dynamic navigators impossible until React Navigation 4.
React Navigation 5 has a new component-based API to configure navigators, which makes dynamic navigators possible:
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
const Tab = createBottomTabNavigator();
function AppNavigator() {
const isRouteEnabled = (routeName) => {
return this.props.route == routeName;
}
return (
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Screen2" component={Screen2} />
{isRouteEnabled('Screen3') && (
<Tab.Screen name="Screen3" component={Screen3} />
)}
</Tab.Navigator>
);
}
const mapStateToProps = (state) => ({ route: state.route });
export default connect(mapStateToProps)(AppNavigator);
Documentation: https://reactnavigation.org/next
Keep in mind that React Navigation 5 is still in alpha.
来源:https://stackoverflow.com/questions/58051853/tabnavigator-redux-with-dynamic-route-configs