React Native 错误:找不到导航对象,您的组件是否位于NavigationContainer中?

zyfwsgd6  于 2023-01-09  发布在  React
关注(0)|答案(3)|浏览(172)

我尝试使用可按按钮从登录屏幕导航到主屏幕。但是,我现在拥有的代码给出了以下错误:* 找不到导航对象。您的组件是否位于NavigationContainer中?*.错误针对第8行(const navigation = useNavigation();).登录按钮.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中最后一个〈View.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;
ct2axkht

ct2axkht1#

useNavigation仅在您的组件位于NavigationContainerNavigator内部时有效,如入门页面中所述:
https://reactnavigation.org/docs/hello-react-navigation

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

HomeScreen将是您的LoginItem

elcex8rz

elcex8rz2#

在我的例子中,我得到这个错误是因为autocomplete添加了错误的import语句。
第一个月
但我需要的是
import { useNavigation } from "@react-navigation/native";
希望这能帮助任何人保存一些时间。

gcxthw6b

gcxthw6b3#

我也正确地传递了params,但是params里面有一个react组件,这就是为什么它会给出这个错误。
//产品不应有React组件props.navigation.navigate(ROUTE_TEST,{产品});

相关问题