Error: Couldn't find a navigation object. Is your component inside NavigationContainer?

Error: Couldn't find a navigation object. Is your component inside NavigationContainer?

我正在尝试使用可按下的按钮从我的登录屏幕导航到主屏幕。但是,我现在的代码出现以下错误:找不到导航对象。您的组件在 NavigationContainer 中吗?。该错误针对第 8 行(const navigation = useNavigation();)。 LoginButton.js:

import React, { Component } from "react";
import { View, Text, Image, Pressable, Button } from "react-native";
import { useNavigation } from "@react-navigation/native";
import styles from "./styles";
import HomeScreen from "../../screens/Home";

const LoginButton = () => {
  const navigation = useNavigation();

  return (
    <View style={styles.container}>
      <Pressable
        onPress={() => navigation.navigate("Home")}
        style={styles.button}
      >
        <Text style={styles.buttontext}>Login</Text>
      </Pressable>
    </View>
  );
};

export default LoginButton;

LoginButton 作为组件插入到最后一个 LoginItem.js:

import React from "react";
import { View, Text, Image } from "react-native";
import styles from "./styles";
import LoginButton from "../LoginButton";
import { createNativeStackNavigator } from "@react-navigation/native-stack";

const Stack = createNativeStackNavigator();

const LoginItem = (props) => {
  return (
    <View style={styles.logincontainer}>
      {/* Background image of the login screen */}
      <Image
        source={require("../../../assets/images/blue-sky-start-screen.jpg")}
        style={styles.loginbackground}
        blurRadius={4}
      ></Image>
      {/* Title of the login screen */}
      <View style={styles.titlecontainer}>
        <Text style={styles.companytitle}>BestelSnel</Text>
      </View>
      {/* Login button */}
      <View style={styles.loginbutton}>
        <LoginButton></LoginButton>
      </View>
    </View>
  );
};

export default LoginItem;

useNavigation 仅当您的组件位于 NavigationContainerNavigator 内时才有效,如入门页面所述:

https://reactnavigation.org/docs/hello-react-navigation

<NavigationContainer>
  <Stack.Navigator>
    <Stack.Screen name="Home" component={HomeScreen} />
  </Stack.Navigator>
</NavigationContainer>

HomeScreen 将是您的 LoginItem

就我而言,我收到此错误是因为自动完成添加了错误的导入语句。

import { useNavigation } from "@react-navigation/core";

但我需要的是:

import { useNavigation } from "@react-navigation/native";

希望这可以帮助任何人节省一些时间。