繁体   English   中英

React Native无法读取属性未定义错误

[英]React Native cannot read property undefined error

我正在开始对本机进行响应,并且尝试通过按下按钮从文本框中输入一个简单的控制台日志值。

我收到错误

无法读取未定义的属性“电子邮件”

该错误发生在console.log上。 我在这里做错了什么?

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);

您需要将getUser函数绑定到类实例。 您可以通过两种方式做到这一点。 一个正在这样的构造函数中做

constructor(){
    super()

    this.state = {
      email: '',
      password: '',
    }
    this.getUser = this.getUser.bind(this);
  }

或者您可以使用像这样的arrow function语法

getUser = () => {
    console.log(this.state.email);
    console.log(this.state.password);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM