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

React Native报错:Cannot read property 'navigate' of undefined 求助

Fixing "Cannot read property 'navigate' of undefined" in Your Modal Button

Hey there, let's get that modal navigation working smoothly! The root cause here is pretty straightforward: your ShowModal component doesn't have access to the navigation prop.

Why this happens:

  • Your WelcomeScreen is a registered screen in your StackNavigator, so React Navigation automatically injects the navigation prop into it.
  • But ShowModal is just a child component of WelcomeScreen—it won't receive the navigation prop automatically unless you explicitly pass it down.

Solution 1: Pass the navigation prop directly to ShowModal

This is the simplest fix for your current setup. Update your WelcomeScreen's render method to pass its own navigation prop to the ShowModal component:

// Inside WelcomeScreen's render() method
return (
  <View>
    {/* Your existing "Get GEO" button */}
    <TouchableOpacity 
      style={[{ paddingTop: 10, paddingBottom: 10, borderRadius: 5, marginBottom: 20, width: '70%', backgroundColor: '#009688' }]}
      activeOpacity={.5}
      onPress={this.props.store.fetchNearestLocation}
    >
      <Text>Get GEO</Text>
    </TouchableOpacity>
    {/* Pass the navigation prop here */}
    <ShowModal navigation={this.props.navigation} />
  </View>
);

Now your ShowModal can access this.props.navigation correctly. You can keep your existing onPress handler for the navigation button (just don't forget to add visible text to the button so users can tap it!):

<TouchableOpacity 
  style={[{ paddingTop: 10, paddingBottom: 10, borderRadius: 5, marginBottom: 20, width: '70%', backgroundColor: '#009688' }]}
  activeOpacity={.5}
  onPress={() => this.props.navigation.navigate('UserScreen')}
>
  <Text>Go to User Screen</Text> {/* Add this text so the button is visible */}
</TouchableOpacity>

Solution 2: Use the withNavigation Higher-Order Component

If you plan to reuse ShowModal in multiple places and don't want to pass the navigation prop every time, use React Navigation's withNavigation HOC to inject the prop automatically.

First, import it at the top of your WelcomeScreen file:

import { withNavigation } from 'react-navigation';

Then wrap your ShowModal component when exporting it:

export default withNavigation(inject("store")(observer(ShowModal)));

With this setup, you don't need to pass the navigation prop from WelcomeScreen—ShowModal will have access to it directly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:32:15