React Navigation Drawer: Dynamically routes and navigation items?

此生再无相见时 提交于 2019-12-07 20:18:29

I understand that you want your drawer navigation to be dynamic in relation to the data received from the API. In that case, you should only create and render the drawer navigation after the api call.

After fetching the categories, iterate through them and build your route config. You should be able to override the navigationOptions and manually set some params (containing your specific category) for each screen.

let routeConfig = {};

categories.map(category => {
    routeConfig[category.key] = {
        screen: CategoryScreen, // your template screen, common to every item
        navigationOptions: (props) => {
            props.navigation.setParams({ category });
        }
    }
});

const DrawerNav = createDrawerNavigation(routeConfig, { /*options*/ });

Then you'll have to render the drawer navigation component manually

render() {
    return (
        <DrawerNav screenProps={{}} />
    );
}

Finally, within CategoryScreen or whatever your screen component is, you can access the category in a way similar to the clasic navigation case: this.props.navigation.state.params.category.

Some notes:

  • The DrawerNav constant is just an example. Most probably you're going to want to make it a class property or a normal variable defined outside of the class but populated within.
  • category.key is yet again an example, you should make sure to replace it with something unique for each category, such as a string representation of the category id.
  • If you want to have different screen components for each category, you can simply pass a different component to screen based on the category in the current .map() iteration.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!