开发者问题收集

React Native 错误未定义不是一个对象(评估“navigation.push”)

2021-07-27
912

我想在单击 MainMenu.js 文件中的按钮后导航到 List.js,但它总是显示此错误:

TypeError:未定义不是对象(评估“navigation.push”)

这是我的 App.js 文件

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { List } from './List';
import { MainMenu } from './MainMenu';

export default function App() {
  return (
    <View style={styles.container}>
      <Text>Open up App.js to stassrt working on your app!</Text>
      <StatusBar style="auto" />
      <MainMenu></MainMenu>
    </View>
  );
}

这是我的 MainMenu.js 文件(我在此文件中有按钮):

import React from 'react';
import { Text, Button, View, StyleSheet } from 'react-native';
import { ScreenContainer } from 'react-native-screens';
import { List } from './List';
import { useNavigation } from '@react-navigation/core';


export const MainMenu = ({navigation}) => (
    
    <View>
      <Text>Hello HOW ARE YsOU</Text>
      <Button title="Click" onPress={() => navigation.push("List")}></Button>
    </View>
    
);
2个回答

在您的 MainMenu 组件中,您需要一个带有键 navigation 作为 props 的对象。但是,您没有将任何 props 传递给 MainMenu ,因此 props 未定义,但您需要一个对象。要解决此问题,请将组件更改为:

import React from 'react';
import { Text, Button, View, StyleSheet } from 'react-native';
import { ScreenContainer } from 'react-native-screens';
import { List } from './List';
import { useNavigation } from '@react-navigation/core';


export const MainMenu = () => {
    const navigation = useNavigation()
    return (
      <View>
        <Text>Hello HOW ARE YsOU</Text>
        <Button title="Click" onPress={() => navigation.push("List")}> 
        </Button>
      </View>
    ); 
};

我们正在使用钩子,而不是 props。

sid c
2021-07-27

我不知道您是如何实现堆栈导航器的,但我认为您的 App.js 文件应该是这样的:

import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { List } from './List';
import { MainMenu } from './MainMenu';

const Stack = createStackNavigator();

export default function App() {
return (
   <NavigationContainer>
     <Stack.Navigator>
        <>
         <Stack.Screen name="Main Menu" component={MainMenu} />
         <Stack.Screen name="List" component={List} />
       </>
    </Stack.Navigator>
  </NavigationContainer>
 );
}

而且我认为您的 MainMenu 组件应该是这样的:

import React from 'react';
import { Text, Button, View, StyleSheet } from 'react-native';
import { ScreenContainer } from 'react-native-screens';
import { List } from './List';

export const MainMenu = ({navigation}) => (
  <View style={styles.container}>
    <Text>Open up App.js to stassrt working on your app!</Text>
    <StatusBar style="auto" />
    <View>
     <Text>Hello HOW ARE YsOU</Text>
     <Button title="Click" onPress={() => navigation.navigate("List")</Button>      
    </View>
  </View>
Jordan Penn
2021-07-28