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

React Native Navigation 5自定义Header报错:scene.route未定义

解决React Navigation 5自定义头部组件的scene.route未定义错误

嘿,这个问题我之前也碰到过!你遇到的TypeError: undefined is not an object (evaluating 'scene.route'),根源是自定义头部组件没有拿到React Navigation传递的必要参数,咱们一步步来修复:

问题原因分析

在你的路由栈配置里,定义header时直接渲染了<CustomHeader2></CustomHeader2>,但没有把React Navigation提供的scene、navigation、previous这些关键props传递给组件。组件内部尝试解构props.scene,但因为没传props,scene是undefined,自然会触发报错。

修复步骤

1. 修改路由栈的header配置

把路由栈里的header函数改成传递props的形式,这样所有需要的参数都会被传给自定义头部组件:

<Stack.Screen 
  name="VenueCard8" 
  component={VenueCard8} 
  headerShown={true} 
  options={({ route }) => ({ 
    title: route.params.venue.name, 
    // 这里把header函数接收的props传递给CustomHeader2
    header: (props) => <CustomHeader2 {...props} /> 
  })} 
/>

2. 给自定义组件加安全防护(可选但推荐)

为了避免后续可能出现的参数缺失问题,可以在组件里加一层判断,或者给props设置默认值,防止意外崩溃:

export default CustomHeader2 = (props = {}) => { 
  const {scene, previous, navigation } = props; 

  // 先检查必要参数是否存在,避免崩溃
  if (!scene?.route?.params?.venue) {
    return <View style={{width: '100%', height: 50, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center'}}>
             <Text>默认标题</Text>
           </View>;
  }

  return ( 
    <View style={{ width:'100%',height:50, flexDirection:'row', alignItems:'center', justifyContent:'space-between', backgroundColor:'white' }}> 
      <View style={{ height:50, flexDirection:'row', alignItems:'center' }}> 
        {previous ? (
          <TouchableOpacity onPress={() => navigation.goBack()} style={{ width:50, height:'100%',flexDirection:'column',alignItems:'center', justifyContent:'center' }}> 
            <MaterialCommunityIcon name="arrow-left" style={{ color:'black', marginRight:0, fontSize:30 }}/> 
          </TouchableOpacity>
        ) : null } 
        <Text style={{ fontSize:18, color:'rgb(68,68,68)',fontWeight:'bold' }}>
          {scene.route.params.venue.name}
        </Text> 
      </View> 
    </View> 
  );
};

这样修改之后,组件就能正确接收到scene参数,访问scene.route.params.venue.name也不会再报错啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:32:31