如何在CustomHeader中同时获取navigation对象与props.children?
解决方案
要让CustomHeader同时获取外部传入的navigation对象和当前激活标签的children,只需将导航器内部的headerProps与外部传入的props合并后传递给CustomHeader即可。
1. 修改底部标签导航器的headerTitle配置
在ClientBottomTabNavigator的screenOptions中,把headerTitle改成以下写法:
headerTitle: (headerProps) => <CustomHeader {...props} {...headerProps} />,
这样CustomHeader就能同时拿到外部传入的navigation,以及导航器内部提供的children(当前激活标签的标题)。
2. 可选:直接用钩子获取导航信息(更简洁)
如果不想依赖props传递导航相关数据,可在CustomHeader中直接使用React Navigation的内置钩子,无需手动传参:
import { useNavigation, useRoute } from '@react-navigation/native'; const CustomHeader = (props) => { const navigation = useNavigation(); const route = useRoute(); // 获取当前激活路由,可替代props.children判断标签 const patient = useSelector(selectActivePatient); const dispatch = useDispatch(); return ( <View> <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'space-between', marginBottom: 4 }}> <Feather name='chevron-left' size={24} onPress={() => { // 根据当前路由自定义返回逻辑 switch(route.name) { case 'Sessions': navigation.navigate('Main'); break; case 'Chart': // 自定义Chart标签的返回行为 break; case 'Goals': // 自定义Goals标签的返回行为 break; } }} color={styles.colors.textInverse} style={{ minWidth: '8%', justifySelf: 'flex-start', alignSelf: 'flex-start' }} /> {/* 其他原有代码 */} </View> {/* 其他原有代码 */} </View> ); };
这种方式更贴合React Navigation的最佳实践,无需手动管理props传递。
完整修改后的底部标签导航器代码
export const ClientBottomTabNavigator = (props) => { const Tab = createBottomTabNavigator(); return ( <Tab.Navigator screenOptions={{ headerShown: true, headerStyle: { backgroundColor: Colors.primary, elevation: 0, shadowOpacity: 0, shadowColor: 'transparent', height: 155, }, headerShadowVisible: false, tabBarStyle: { backgroundColor: Colors.primary }, headerTintColor: Colors.light, // 合并外部props和内部headerProps headerTitle: (headerProps) => <CustomHeader {...props} {...headerProps} />, tabBarActiveTintColor: Colors.light, tabBarInactiveTintColor: Colors.lightInactive, tabBarActiveBackgroundColor: Colors.primary, tabBarInactiveBackgroundColor: Colors.primary, }} initialRouteName={'Sessions'} > <Tab.Screen name='Sessions' component={SessionsTab} options={{ tabBarLabel: 'SESSIONS', tabBarIcon: ({ color, size }) => <FontAwesome name='street-view' color={color} size={size} />, }} /> <Tab.Screen name='Chart' component={ChartTab} options={{ tabBarLabel: 'CHARTS', tabBarIcon: ({ color, size }) => <FontAwesome name='id-badge' color={color} size={size} />, }} /> <Tab.Screen name='Goals' component={GoalsTab} options={{ tabBarLabel: 'EDIT GOALS', tabBarIcon: ({ color, size }) => <FontAwesome name='trophy' color={color} size={size} />, }} /> </Tab.Navigator> ); };
内容的提问来源于stack exchange,提问作者Muirik
相关产品推荐
相关产品推荐

