如何在选项卡导航中访问导航道具 - 反应导航 [英] How to access navigation prop in tabs navigation - react navigation
问题描述
我需要在所有屏幕上放置一个浮动按钮,我将它放在具有绝对位置的底部标签导航器中,但我无法为其设置 onPress 导航..如何在标签导航器中访问 navigation.navigate?
I need to put a floating button appears in all screens, i put it in bottom tab navigator with absolute position but i couldn't set the onPress navigation for it.. how can i access navigation.navigate in tab navigator?
我的代码
MoreStack.navigationOptions = {
tabBarLabel: 'More',
tabBarIcon: ({ focused, navigation }) => (
<View>
<TabBarIcon
focused={focused}
name={Platform.OS === 'ios' ? 'ios-more' : 'md-more'}
type='ionicon'
/>
<View
style={{
flex: 1,
position: 'absolute',
bottom: 20,
alignItems: 'center',
right: 10,
}}
>
<TouchableOpacity onPress={() => navigation.navigate('Chat')}>
<Image
source={require('../assets/chat.png')}
style={{ alignSelf: 'center', height: 60, width: 60 }}
/>
</TouchableOpacity>
</View>
</View>
),
};
推荐答案
要能够在任何地方导航,请保留对 NavigationContainer
的引用.
To able to navigate anywhere, keep a reference of the NavigationContainer
.
示例:我创建了一个 NavigationService
,如下所示:
Example: i created a NavigationService
like the following:
import { CommonActions, StackActions } from "@react-navigation/native";// react navigation 5
import { NavigationActions, StackActions } from "react-navigation"; // react navigation 4
export default class NavigationService {
// core navigator
private static navigator;
// sets the core navigator
static setTopLevelNavigator(navigatorRef) {
NavigationService.navigator = navigatorRef;
}
// naviget to a route
static navigate(name, params?) {
NavigationService.navigator.dispatch(CommonActions.navigate({ name, params }));
}
static goBack() {
return NavigationService.navigator.dispatch(CommonActions.goBack());
}
static popToTop() {
NavigationService.navigator.dispatch(StackActions.popToTop())
}
}
在你的 App.js 中:
And in your App.js:
<NavigationContainer ref={(ref) => NavigationService.setTopLevelNavigator(ref)}>
//
</NavigationContainer>
现在 NavigationService
有了对 NavigationContainer
的引用,因此您可以通过以下方式导航到任何地方:
Now the NavigationService
has a reference of the NavigationContainer
, thus you can navigate anywhere by doing:
NavigationService.navigate("SomeScreen");
如果您使用的是 React 导航 4,请将 CommonActions
替换为 NavigationActions
.
If you are using react navigation 4 replace CommonActions
with NavigationActions
.
这篇关于如何在选项卡导航中访问导航道具 - 反应导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!