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

React Navigation Native中navigation.navigate报undefined错误求助

问题描述

自定义Home按钮无法跳转首页,触发「undefined错误」。推测原因是Stack Navigator配置在主文件中,不知道如何让当前BattleScreen文件获取navigation实例,谷歌搜索和查阅官方文档都未解决问题。

相关代码

import React from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import CustomButton from './CustomButton';
import { useFonts } from 'expo-font';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import player from './Player';
import App from './App';
import usePotion from './UsePotion';
import { useState } from 'react';
import { useEffect } from 'react';

function BattleScreen({ navigation }) {
    
    const [fontsLoaded, error] = useFonts({
        'Valorax': require('./Fonts/Valorax.otf'),
      });
    
      if (!fontsLoaded) {
        return <Text>Loading...</Text>;
      }

    return (
      <View style={styles.container}>
        <Text style={styles.text}>{player.potions}</Text>
        <View style={styles.topHalf}>
        </View>
        <View style={styles.bottomHalf}>
          <View style={styles.buttonRow}>
            <CustomButton onPress={() => handleAttack()} title='Attack'></CustomButton>
            <CustomButton onPress={() => handleMagic()} title='Magic'></CustomButton>
          </View>
          <View style={styles.buttonRow}>
            <CustomButton onPress={usePotion()} title='Use Potion'></CustomButton>
            <CustomButton onPress={() => handleRun()} title='Run'></CustomButton>
            <CustomButton onPress={() => navigation.navigate('Home')} title="Home"></CustomButton>
          </View>
        </View>
      </View>
    );
  }
  
  const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#000000',
    },
    topHalf: {
      flex: 1,
      color: 'white',
    },
    bottomHalf: {
      flex: 1,
      flexDirection: 'row',
      flexWrap: 'wrap'
    },
    buttonRow: {
      flex: 1,
      flexDirection: 'row',
      justifyContent: 'space-evenly',
      flexWrap: 'wrap'
    },
    text: {
        fontSize: 90,
        color: 'white',
        fontFamily: "Valorax",
    }
  });

export default BattleScreen;
解决方案

1. 确认主文件的Stack Navigator配置

确保主文件(如App.js)中已正确注册BattleScreen和Home页面,且BattleScreen是通过Stack Navigator导航进入的,而非直接渲染。示例配置:

// 主文件(App.js)
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import BattleScreen from './BattleScreen';
import HomeScreen from './HomeScreen';

const Stack = createNativeStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Battle" component={BattleScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

2. 确保navigation实例正确获取

  • 如果BattleScreen是通过navigation.navigate('Battle')跳转进入的,props中的navigation会自动传递,无需额外操作。
  • 如果必须直接渲染BattleScreen,可使用useNavigation钩子手动获取实例:
// 修改BattleScreen的navigation获取方式
import { useNavigation } from '@react-navigation/native';

function BattleScreen() {
  const navigation = useNavigation(); // 手动获取navigation实例
  
  // 其余代码保持不变
  return (
    // ... 原有JSX结构
  );
}

3. 修复其他潜在错误

  • 检查Stack Navigator中Home页面的name属性是否为'Home',和navigation.navigate('Home')的参数完全一致(大小写敏感)。
  • 补充代码中未定义的handleAttack、handleMagic、handleRun函数,避免点击按钮报错:
function BattleScreen({ navigation }) {
  const handleAttack = () => {
    // 实现攻击逻辑
  };
  
  const handleMagic = () => {
    // 实现魔法攻击逻辑
  };
  
  const handleRun = () => {
    // 实现逃跑逻辑
  };
  
  // 其余代码不变
}
  • 修改Use Potion按钮的onPress属性,避免组件渲染时直接执行usePotion():
<CustomButton onPress={() => usePotion()} title='Use Potion'></CustomButton>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:45:46