如何在标签导航中访问导航道具-反应导航

时间:2020-07-12 18:49:27

标签: reactjs react-native react-navigation react-navigation-bottom-tab

我需要在所有屏幕上显示一个浮动按钮,将其置于绝对位置的底部选项卡导航器中,但无法为其设置onPress导航。如何在选项卡导航器中访问navigation.navigate? / p>

我的代码

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>
  ),
};

1 个答案:

答案 0 :(得分:0)

要能够导航到任何地方,请保留NavigationContainer的引用。

示例:我创建了一个NavigationService,如下所示:

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中:

<NavigationContainer ref={(ref) => NavigationService.setTopLevelNavigator(ref)}>
// 
</NavigationContainer>

现在NavigationService拥有NavigationContainer的引用,因此您可以通过以下操作导航到任何地方:

NavigationService.navigate("SomeScreen");

如果您使用反应导航4将CommonActions替换为NavigationActions