问题
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