You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native跳转组件报错undefined is not an object(evaluating 'navigation.navigate')

报错核心原因

navigation对象为undefined是因为当前Welcome组件没有被 React Navigation 自动注入navigation属性,只有被注册为导航栈的屏幕组件,才会默认在props中拿到该对象。

解决方法

方法1:正确配置导航栈(推荐)

你需要在根组件(通常是App.js)中完成导航栈的注册,将Welcome和NameView都注册为栈内屏幕,示例代码如下:

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Welcome from './landing.js'; // 替换为你的Welcome组件实际路径
import NameView from './name_view.js';

const Stack = createNativeStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Welcome">
        {/* 注册两个屏幕组件,注册后组件props会自动注入navigation对象 */}
        <Stack.Screen name="Welcome" component={Welcome} />
        <Stack.Screen name="NameView" component={NameView} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

配置完成后不要直接在根组件渲染Welcome,改为渲染上述配置好的导航容器即可。

方法2:手动获取navigation对象

如果你的Welcome组件没有直接注册为屏幕,但是外层已经包裹了NavigationContainer,可以用useNavigation钩子手动获取对象,修改landing.js代码如下:

import React from 'react'
import { View, Text, Image, StyleSheet, TouchableHighlight } from 'react-native'
import { useNavigation } from '@react-navigation/native'; // 导入钩子
import NameView from './name_view.js';

export default function Welcome() {
  const navigation = useNavigation(); // 手动获取navigation对象

  return (
    <View style={WelcomeStyles.Welcome}>
      <TouchableHighlight style={WelcomeStyles.Button} activeOpacity={0.6} underlayColor="#11132b" onPress={() => navigation.navigate('NameView')}>
              <View>
                  <View style={WelcomeStyles.ButtonBG} />
                  <Text style={WelcomeStyles.GetStarted}>Get Started</Text></View>
          </TouchableHighlight>
    </View>
  )
}

注意事项

  • 请确保已完整安装所有导航依赖:@react-navigation/native、react-native-screens、react-native-safe-area-context、@react-navigation/native-stack
  • landing.js中无用的NavigationContainer、createNativeStackNavigator导入可以删除,避免冗余

内容的提问来源于stack exchange,提问作者Jay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:18:01