[英]TypeError: undefined is not an object (evaluating '_this3.state.bind')
App.js code: App.js 代码:
import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component {
constructor(props){
super(props);
this.state={count:0};
this.incrementCount=this.incrementCount.bind(this)
}
incrementCount(){
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text style={styles.homeScreen}>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => {
this.incrementCount();
this.props.navigation.navigate('Details');
}}
/>
</View>
);
}
}
class DetailsScreen extends React.Component {
constructor(props){
super(props);
this.state=this.state.bind(this)
this.incrementCount=this.incrementCount.bind(this)
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Hello </Text>
</View>
);
}
}
const AppNavigator = createStackNavigator(
{
Home: HomeScreen,
Details: DetailsScreen,
},
{
initialRouteName: 'Home',
}
);
const styles= StyleSheet.create({
homeScreen:{
}
});
export default createAppContainer(AppNavigator);
I wanted to increment a number (0), every time the user goes to the details(the second page) page.我想增加一个数字(0),每次用户进入详细信息(第二页)页面时。 The incremented number should be displayed on the details(the second page) page.
增加的数字应显示在详细信息(第二页)页面上。
I am a beginner in react native and I don't know how to use state in different classes.我是 React Native 的初学者,我不知道如何在不同的类中使用 state。 Do explain the concept of state along with the solution.
一定要解释状态的概念以及解决方案。
You have to send your count
as prop to your DetailsPage
.您必须将您的
count
作为道具发送到您的DetailsPage
。 So in code it will look like this:所以在代码中它看起来像这样:
<Button
title="Go to Details"
onPress={() => {
this.incrementCount();
this.props.navigation.navigate('Details',{count:this.state.count});
}}/>
And in your DetailsScreen you have to access it like this:在您的 DetailsScreen 中,您必须像这样访问它:
class DetailsScreen extends React.Component {
constructor(props){
super(props);
//Remove these lines this is causing error and this is wrong
//this.state=this.state.bind(this)
//this.incrementCount=this.incrementCount.bind(this)
}
render() {
let count = this.props.navigation.getParam('count')
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>You were here {count} times </Text>
</View>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.