反应本机导航错误。我该如何解决?

时间:2020-10-21 20:57:18

标签: react-native react-navigation react-navigation-stack

在此代码块中,我想使用navigation.navigate在主屏幕和个人资料屏幕之间切换。但是,当我运行该应用程序时,出现以下错误:找不到变量导航。 我一直在寻找解决方案,但似乎找不到。 这是代码:

import 'react-native-gesture-handler';
import * as React from 'react';
import {View, Text, Button} from 'react-native';
import { NavigationContainer, StackActions } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

const HomeScreen = () => {
  return(
    <View>
      <Text>Home Screen</Text>
      <Button title="Go to Profile Screen" onPress={()=> navigation.navigate("Profile")}/>
    </View>
  );

}
const ProfileScreen = () => {
  return(
    <View>
      <Text>Profile Screen</Text>
      <Button title="Go to Home Screen" onPress={() => navigation.navigate("Home")}/>
    </View>
  );

}
export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen 
          name="Profile" 
          component={ProfileScreen}
          options={{ title: '' }}
        />
        <Stack.Screen 
          name="Home" 
          component={HomeScreen}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以从navigation获取props对象。代码示例:

const HomeScreen = ({navigation}) => {
  return(
    <View>
      <Text>Home Screen</Text>
      <Button title="Go to Profile Screen" onPress={()=> navigation.navigate("Profile")}/>
    </View>
  );
}