尝试在两个站点 React Native 之间导航时,未定义不是对象(评估 'navigation.navigate')

Undefined is not an object (evaluating 'navigation.navigate') when trying to navigate between two sites React Native

我尝试在 React Native 应用程序的两个页面之间导航。我的实现不断出现错误,但我不知道为什么。

我在 React Native 应用程序中对“主页”和“设置”站点进行了以下设置,并根据 documentation:

调整了 Navigator

App.js

import Home from "./Home";
import { NavigationContainer } from '@react-navigation/native';

export default function App() {
  return <NavigationContainer><Home/></NavigationContainer>
}

Home.jsx

const Home = ({ navigation }) => {
  return (
    <View style={["some style...", {}]}>
      <View style={["some style..."]}>
        <TouchableOpacity onPress={() =>
        navigation.navigate('Settings')}>
          <Image "some image..."/>
        </TouchableOpacity>
      </View>
    </View>

Settings.jsx

应该渲染的组件。

MyStack.jsx

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Home from './Home';
import Settings from './Settings';

const Stack = createNativeStackNavigator();

const MyStack = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={Home}
        />
        <Stack.Screen name="Settings" component={Settings} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

我得到 undefined is not an object (evaluating 'navigation.navigate')。还将 this.props 添加到 navigation.navigate('Settings') 抛出和错误。我只是无法访问我的导航器。

您似乎正在设置导航器但从未使用它,因为在 App.js 中您只是调用 <Home/>

  1. App.js 更改为以下代码。

Use the correct path for the import.

import MyStack from "./MyStack";

export default function App() {
  return <MyStack/>
}
  1. MyStack.jsx末尾添加:
export default MyStack;