带有动态路由配置的 TabNavigator/redux [英] TabNavigator / redux with dynamic route configs
问题描述
我正在开发一个带有底部选项卡导航器的 react-native 应用程序,并且希望导航选项取决于正在显示的屏幕,例如:
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 />
}
}
我遇到的问题是在这个类中访问 this.props,目前它总是未定义的.如果可能的话,我希望它使用我的 redux 存储中的值,但是如果我将 AppNavigator 包装在 connect() 调用中,使其成为更高级别的组件导航根本不再起作用(出于我的原因)不明白):
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 很简单:
export default class App extends React.Component {
render() {
return (
<Provider store={appStore}>
<AppNavigator />
</Provider>
);
}
}
我是否遗漏了什么 - 是否有可能有一个具有动态行为的导航器,该行为取决于存储在 redux 中的值?
Am I missing something - is it possible to have a navigator with dynamic behavior that depends on values stored in redux?
推荐答案
当前版本的 React Navigation 有一个静态配置 API,这意味着所有配置都必须在渲染之外完成.这使得动态导航器等用例在 React Navigation 4 之前是不可能的.
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 有一个新的基于组件的 API 来配置导航器,这使得动态导航器成为可能:
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);
文档:https://reactnavigation.org/next
请记住,React Navigation 5 仍处于 alpha 阶段.
Keep in mind that React Navigation 5 is still in alpha.
这篇关于带有动态路由配置的 TabNavigator/redux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!