I have just started learning react-native.... Doing a pet project now.... In the app there's a button on clicking it navigates to another screen. I get the following error saying " undefined is not an object (evaluating 'this.props.navigate') " The following are the files
index.js
import React from "react";
import Navigator from "./config/routes";
export default () => <Navigator />;
The code in my config/routes.js
import { StackNavigator } from "react-navigation";
import Home from "../screens/Home";
import List from "../screens/List";
export default StackNavigator({
Home: {
screen: Home,
navigationOptions: {
header: () => null
}
},
List: {
screen: List
}
});
and my component file Home.js which has the button which on click clicking navigates to another screen
/*all import statements*/
class Home extends Component {
handlePressBaseCurrency() {
console.log("base currency button clicked");
this.props.navigation.navigate("List"); /* error from this line */
}
render() {
return (
<UserInput
currencyShort={TEMP_BASE_CURRENCY}
onPress={this.handlePressBaseCurrency}
defaultValue={TEMP_BASE_PRICE}
keyboardType="numeric"
onChangeText={this.handleTextChange}
/>
);
}
}
Please help!!! Thanks in advance :D
this
is not bound correctly in handlePressBaseCurrency
. You can:
Explicitly bind this
in your constructor:
constructor(props) { super(props); this.handlePressBaseCurrency = this.handlePressBaseCurrency.bind(this); }
From the React Docs on handling events :
If calling bind annoys you, there are two ways you can get around this. If you are using the experimental public class fields syntax , you can use class fields to correctly bind callbacks:
handlePressBaseCurrency = () => { console.log("base currency button clicked"); this.props.navigation.navigate("List"); };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.