Open one of two drawers from button in react navigation 5

眉间皱痕 提交于 2020-05-17 06:11:27

问题


It was previously possible to open a specific drawer from a button, using getCustomActionCreators, prior to v5 of React Navigation.

An example of doing that is here: React Native two drawers on one screen

However, it looks like this function has been removed. Is there a way to do this in React Navigation 5?


回答1:


This is possible by creating a custom router.

Here are a few key pieces of insight:

  • navigators bubble up actions which they don't handle. This means that we need to create a custom action for each of our drawers.
  • In order to create custom actions, we need to create custom routers.
  • In order to use the custom routers, we need to build a new navigator.

Custom action:

export const openMenuDrawerAction = { type: 'OPEN_MENU_DRAWER' };

Helper function to dispatch custom action (optional)

export const openMenuDrawer = navigation => {
    navigation.dispatch(openMenuDrawerAction);
};

Custom router

const MenuDrawerRouter = options => {
    const router = DrawerRouter(options);

    const oldGetStateForAction = router.getStateForAction;

    return {
        ...router,
        getStateForAction: (state, action, options) => {
            switch (action.type) {
                case 'OPEN_MENU_DRAWER':
                    return oldGetStateForAction(state, DrawerActions.openDrawer(), options);
                default:
                    return oldGetStateForAction(state, action, options);
            }
        }
    };
};

Custom navigator

This is based on the code from createDrawerNavigator.

const createDrawerNavigatorWithRouter = router => {
    // eslint-disable-next-line react/prop-types
    function DrawerNavigator({ initialRouteName, openByDefault, backBehavior, children, screenOptions, ...rest }) {
        const { state, descriptors, navigation } = useNavigationBuilder(router, {
            initialRouteName,
            openByDefault,
            backBehavior,
            children,
            screenOptions
        });

        return <DrawerView {...rest} state={state} descriptors={descriptors} navigation={navigation} />;
    }

    return createNavigatorFactory(DrawerNavigator)();
};

Create navigator instance Now instead of creating a navigator with const Drawer = createDrawerNavigator(), we create it with const Drawer = createDrawerNavigatorWithRouter(MenuDrawerRouter).

Repeat The above steps create a single drawer. Now you'd duplicate the above (with different action names) for a second drawer. createDrawerNavigatorWithRouter can be reused without duplication, as it's generic to drawer navigators.



来源:https://stackoverflow.com/questions/61742796/open-one-of-two-drawers-from-button-in-react-navigation-5

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