简体   繁体   中英

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. What am I doing wrong here?

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. 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

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

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.

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