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

React Native组件间导航时this.props.navigation未定义问题求助

React Native页面跳转报错:undefined is not an object evaluating this.props.navigation.navigate

嘿,这个问题我之前也碰到过!你遇到的错误本质是你的Header组件没有拿到navigation属性——只有直接注册在导航栈里的屏幕组件才会自动获得这个属性,而Header作为子组件,得手动给它传或者用工具注入才行。

先看看你的Header代码片段:

import React, { Component } from "react";
import { View, Text, StyleSheet, Button, Image } from "react-native";
import Icon from "react-native-vector-icons/FontAwesome";

export default class Header extends Component {
 constructor(props) {
 super(props);
 this.state = {};
 }
 render() {
 return (
 <View style={styles.container}>
 {/* 这里应该有触发跳转的按钮或元素 */}
 </View>
 );
 }
}

下面给你两种解决办法,按需选择:

解决方案1:手动传递navigation属性

如果你只在少数几个屏幕里用这个Header,最简单的方式就是在引入Header的地方,把当前屏幕的navigation属性传过去。

比如你在HomeScreen里用Header:

// HomeScreen.js
import Header from './header';

class HomeScreen extends Component {
  render() {
    return (
      <View>
        {/* 把当前屏幕的navigation传给Header */}
        <Header navigation={this.props.navigation} />
        {/* 其他页面内容 */}
      </View>
    );
  }
}

之后在Header里,你就能正常用this.props.navigation.navigate('目标页面名称')来跳转了。

解决方案2:使用withNavigation高阶组件(推荐)

如果你的Header要在很多地方复用,每次手动传navigation太麻烦,就用withNavigation高阶组件来自动给Header注入navigation属性:

  1. 先在Header组件里导入withNavigation:
import React, { Component } from "react";
import { View, Text, StyleSheet, Button, Image } from "react-native";
import Icon from "react-native-vector-icons/FontAwesome";
// 新增这行导入
import { withNavigation } from '@react-navigation/native';
  1. 用withNavigation包裹你的Header组件:
// 把原来的export default替换成这个
export default withNavigation(Header);

这样不管你在哪个组件里引入Header,它都能直接拿到navigation属性,不用再手动传递啦!

最后提醒下:确保你的项目已经正确配置了React Navigation的导航容器(比如NavigationContainer),并且所有需要跳转的页面都已经注册到导航栈里哦~

内容的提问来源于stack exchange,提问作者Md Nahid Hasan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:57:24