问题
I've been trying to get up and running with react navigation but I run into a problem when I try to move navigation items into their own components.
HomeScreen.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text
} from 'react-native';
import NavButton from '../components/NavButton'
class HomeScreen extends Component {
render() {
return (
<View style={styles.container}>
<Text>
Hello World
</Text>
<NavButton
navigate={this.props.navigator}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
export default HomeScreen;
Then in the NavButton component I try to navigate to the new screen.
class NavButton extends Component {
render() {
return (
<View>
<Button
title="Go to About"
onPress={() => this.props.navigator.navigate('About')}
/>
</View>
);
}
}
export default NavButton;
But I keep getting the error "Cannot read property 'navigate' of undefined.
Here is my Router.js file as well.
import React from 'react';
import {StackNavigator} from 'react-navigation';
import HomeScreen from '../screens/HomeScreen'
import AboutScreen from '../screens/AboutScreen'
export const AppNavigator = StackNavigator({
Home: {
screen: HomeScreen
},
About: {
screen: AboutScreen
}
})
回答1:
If you rename navigate={this.props.navigator}
to navigator={this.props.navigation}
, it should work because in NavButton you are calling this.props.navigator.navigate
.
回答2:
An ordinary component that is not a screen component will not receive the navigation prop by default.
To resolve this exception, you could pass the navigation prop in to NavButton when you render it from a screen, like so: <NavButton navigation={this.props.navigation} />
Alternatively, we can use the withNavigation
function to provide the navigation prop automatically
import { withNavigation } from 'react-navigation';
class NavButton extends React.Component {
render() {
return (
<Button
title="Back"
onPress={() => {
this.props.navigation.goBack();
}}
/>
);
}
}
// withNavigation returns a component that wraps NavButton and passes in the
// navigation prop
export default withNavigation(NavButton);
refer: https://reactnavigation.org/docs/en/connecting-navigation-prop.html
回答3:
Make sure you are compiling ES6
if not simply use this.props.navigation or this.props.navigation.navigate whatever you need
来源:https://stackoverflow.com/questions/42793844/react-navigation-cannot-read-property-navigate-of-undefined