Jef*_*ong 5 react-native react-navigation
我正在尝试使用可按按钮从登录屏幕导航到主屏幕。但是,我现在的代码出现以下错误:无法找到导航对象。您的组件位于 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;
Run Code Online (Sandbox Code Playgroud)
LoginButton 作为组件插入到最后一个 <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;
Run Code Online (Sandbox Code Playgroud)
useNavigation仅当您的组件位于入门页面上提到的aNavigationContainer和 a之内时才有效:Navigator
https://reactnavigation.org/docs/hello-react-navigation
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
Run Code Online (Sandbox Code Playgroud)
HomeScreen将是你的LoginItem
就我而言,我收到此错误是因为自动完成添加了错误的导入语句。
import { useNavigation } from "@react-navigation/core";
但我需要的是:
import { useNavigation } from "@react-navigation/native";
希望这可以帮助任何人节省一些时间。
| 归档时间: |
|
| 查看次数: |
13720 次 |
| 最近记录: |