React Native报错:Cannot read property 'navigate' of undefined 求助
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
WelcomeScreenis a registered screen in yourStackNavigator, so React Navigation automatically injects thenavigationprop into it. - But
ShowModalis just a child component ofWelcomeScreen—it won't receive thenavigationprop 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

