首页 > 解决方案 > 使用“导航”作为组件的功能

问题描述

我正在尝试在本机反应中使用导航,但是当我尝试使用带有导航(LogIn)的组件时,它给了我一个错误

 <Login/>

标签。

它说导航是未定义的,所以我将导航作为道具传递,但没有成功

应用程序.js

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { SafeAreaView, StyleSheet, Text, View } from 'react-native';
import Login from "./assets/code/Login.js";
import { NavigationContainer, StackActions } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import 'react-native-gesture-handler';

const Stack = createStackNavigator();

export default function App({ navigation }) {

  return (


    <NavigationContainer>
    <Stack.Navigator>
      <Stack.Screen

        name="Welcome to dog app, and I hate react"
        component={HomePage}
        
        />
    </Stack.Navigator>
  </NavigationContainer>
  );

}


function HomePage({ navigation }) {

  return (
    <View style={styles.container}>
      <View>
        <Text> {""}Welcome to dogappcoolapp app</Text>
      </View>
      <View style={styles.blue}>
        <Login navigate={ navigation } style={styles.blue} />
      </View>
    </View>

  )


}

错误在这一行

        <Login navigate={ navigation } style={styles.blue} />

错误是错误

登录功能在

登录.js

import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, Script, Alert } from 'react-native';
import { NavigationContainer, StackActions, } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import 'react-native-gesture-handler';

const Stack = createStackNavigator();

export function Login({navigation}) {


  if (true)
    return (
      
      navigation.navigate('WelcomePage')

    );

}

function WelcomePage () {
  return (

    <View>
      <Button title="enter" />
      <Text> dog app dog woof-app{"\n\n\n\n\n\n\n\n\n"}OMG!! YOU ARE LOGGED IN! WELCOME!{"\n\n\n\n\n"}</Text>
    </View>

  );
}


const styles = StyleSheet.create({
  blue: {
    flex: 2,
    backgroundColor: "dodgerblue",
    alignItems: 'center',
    justifyContent: 'center',
  },
});



export default Login;

如果我从函数 LogIn 中删除所有导航道具和标签,那么我可以将 LogIn 用作组件<LogIn/>,但不能与导航一起使用,我尝试将其与

导航={导航}

(就像我发布的代码一样)

我试过没有它,我不断收到类似的错误。

如何将 LogIn 用作带有</>标签的组件,同时仍然具有导航组件?

标签: javascriptreact-native

解决方案


逻辑是正确的,在子组件中,您可以传递一个导航道具来访问导航,但是您将导航对象传递给一个名为 的道具navigate <Login navigate={ navigation } style={styles.blue} />,难怪它是未定义的,您应该在登录组件中将其作为导航接收。

export function Login({navigation}) { //<-- here you have navigation where the prop name that you pass is navigate.

所以应该是

export function Login({navigate}) {
...
navigate.navigate('...')

或者您应该将您的道具重命名为navigation,然后您navigation.navigate将不再是未定义的。


推荐阅读