从反应导航5中的按钮打开两个抽屉之一 [英] Open one of two drawers from button in react navigation 5
问题描述
在React Navigation v5之前,以前可以使用getCustomActionCreators
通过按钮打开特定的抽屉.
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
但是,似乎该功能已被删除.在React Navigation 5中有没有办法做到这一点?
However, it looks like this function has been removed. Is there a way to do this in React Navigation 5?
推荐答案
这可以通过创建自定义路由器来实现.
This is possible by creating a custom router.
以下是一些关键的见解:
Here are a few key pieces of insight:
- 导航器会冒起他们无法处理的动作.这意味着我们需要为每个抽屉创建一个自定义动作.
- 为了创建自定义动作,我们需要创建自定义路由器.
- 为了使用自定义路由器,我们需要构建一个新的导航器.
自定义操作:
export const openMenuDrawerAction = { type: 'OPEN_MENU_DRAWER' };
帮助程序功能,用于分派自定义操作(可选)
export const openMenuDrawer = navigation => {
navigation.dispatch(openMenuDrawerAction);
};
自定义路由器
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);
}
}
};
};
自定义导航器
这是基于createDrawerNavigator中的代码.
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)();
};
创建导航器实例
现在,我们不再使用const Drawer = createDrawerNavigator()
创建导航器,而是使用const Drawer = createDrawerNavigatorWithRouter(MenuDrawerRouter)
创建导航器.
Create navigator instance
Now instead of creating a navigator with const Drawer = createDrawerNavigator()
, we create it with const Drawer = createDrawerNavigatorWithRouter(MenuDrawerRouter)
.
重复
以上步骤创建了一个抽屉.现在,您将上述内容(具有不同的动作名称)复制到第二个抽屉中. createDrawerNavigatorWithRouter
可以重复使用而无需重复,因为它是抽屉式导航器的通用选项.
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.
这篇关于从反应导航5中的按钮打开两个抽屉之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!