[英]React Native cannot read property undefined error
I'm starting out on react native and I'm trying to do a simple console log the value from the text box when a button is pressed. 我正在开始对本机进行响应,并且尝试通过按下按钮从文本框中输入一个简单的控制台日志值。
I am getting the error 我收到错误
Cannot read property 'email' of undefined
无法读取未定义的属性“电子邮件”
. 。 The error is happening on the console.log.
该错误发生在console.log上。 What am I doing wrong here?
我在这里做错了什么?
LoginPage.js LoginPage.js
import React, {Component} from 'react';
import {AppRegistry, Text, View, TextInput, Button} from 'react-native';
export default class LoginPage extends Component{
constructor(){
super()
this.state = {
email: '',
password: '',
}
}
static navigationOptions = {
headerTitle: 'Login',
};
getUser(){
/* fetch('http://192.168.1.12:8000/login')
.then(response => response.json())
.then(response => {
console.log(response);
});
*/
console.log(this.state.email);
console.log(this.state.password);
}
render(){
return(
<View>
<Text>Login Page</Text>
<TextInput
placeholder = "Email"
onChangeText={(text) => this.setState({email: text})}
//value={this.state.textValue}
//onChangeText={(value) => this.onChangeText(value)}
//onSubmitEditing={this.onSubmit}
/>
<TextInput
placeholder = "Password"
secureTextEntry={true}
onChangeText={(text) => this.setState({password: text})}
//value={this.state.textValue}
//onChangeText={(value) => this.onChangeText(value)}
//onSubmitEditing={this.onSubmit}
/>
<Button
//onPress={() => this.props.navigation.navigate('RegisterPage')}
title="Login"
accessibilityLabel="Login"
onPress={this.getUser}
/>
</View>
);
}
}
AppRegistry.registerComponent('LoginPage', () => LoginPage);
You need to bind the getUser
function to the class instance. 您需要将
getUser
函数绑定到类实例。 You can do that in two way. 您可以通过两种方式做到这一点。 One is doing it in constructor like this
一个正在这样的构造函数中做
constructor(){
super()
this.state = {
email: '',
password: '',
}
this.getUser = this.getUser.bind(this);
}
Or you can use arrow function
syntax like this 或者您可以使用像这样的
arrow function
语法
getUser = () => {
console.log(this.state.email);
console.log(this.state.password);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.