更新时间:2023-01-05 16:44:02
先看DrawerItemList 不允许除屏幕外的任何其他内容.
To begin with , the code of DrawerItemList doesnt allow anything else except for screens to be there.
但这只是您必须传递的另一个组件.
But its just another component that you have to pass.
因此,处理此问题的最简单方法是使用源代码创建您自己的 DrawerItemList 版本,并可以选择传递自定义 onPress 函数.
So the easiest way to handle this would be to create your own version of DrawerItemList using the source code and have the option to pass a custom onPress function.
自定义组件看起来像这样,我已经评论了我修改的地方.
The custom component would look like this, I've commented the places that i modified.
import * as React from 'react';
import {
CommonActions,
DrawerActions,
DrawerNavigationState,
ParamListBase,
useLinkBuilder,
} from '@react-navigation/native';
import { DrawerItem } from '@react-navigation/drawer';
export default function CustomDrawerList({
state,
navigation,
descriptors,
activeTintColor,
inactiveTintColor,
activeBackgroundColor,
inactiveBackgroundColor,
itemStyle,
labelStyle,
}: Props) {
const buildLink = useLinkBuilder();
return state.routes.map((route, i) => {
const focused = i === state.index;
//Access the custom onPress that is passed as an option
const { title, drawerLabel, drawerIcon, onPress } = descriptors[route.key].options;
return (
<DrawerItem
key={route.key}
label={
drawerLabel !== undefined
? drawerLabel
: title !== undefined
? title
: route.name
}
icon={drawerIcon}
focused={focused}
activeTintColor={activeTintColor}
inactiveTintColor={inactiveTintColor}
activeBackgroundColor={activeBackgroundColor}
inactiveBackgroundColor={inactiveBackgroundColor}
labelStyle={labelStyle}
style={itemStyle}
to={buildLink(route.name, route.params)}
onPress={
//if onPress is available use that or call the usual navigation dispatch
// i also passed the navigation so that we can use it in our custom calls
onPress
? () => onPress(navigation)
: () => {
navigation.dispatch({
...(focused
? DrawerActions.closeDrawer()
: CommonActions.navigate(route.name)),
target: state.key,
});
}
}
/>
);
});
}
抽屉看起来像这样,我们将 onPress 作为选项传递
And the drawer would look like this, we pass the onPress as an option
<Drawer.Navigator
initialRouteName="Home"
drawerContent={(props) => {
return (
<DrawerContentScrollView {...props}>
<CustomDrawerList {...props} />
</DrawerContentScrollView>
);
}}>
<Drawer.Screen name="Home" component={PlaceholderPage} />
<Drawer.Screen name="Custom" component={PlaceholderPage} options={{
onPress:()=>alert(123)
}}/>
<Drawer.Screen name="About" component={PlaceholderPage} />
</Drawer.Navigator>
你可以在这里查看小吃https://snack.expo.io/@guruparan/custom-button-抽屉内