liz
liz

Reputation: 39

onChange react native

I have a problem, when I put the user : 1 and password 123 appears to me in console empty strings and I do not understand why someone can help me?

export default class App extends React.Component {

  // Setting up Login Activity title.
  constructor(props) {
    super(props)
    this.state = { UserName: '',Userpassword: ''}

    this.login = this.login.bind(this);
    this.onChange = this.onChange.bind(this)

  }


onChange(e) {
  this.setState({ [e.target.name]: e.target.value });
  console.log(this.state);
}



<TextInput

          placeholder="Enter User Name"  
       
          onChange={this.onChange}

          underlineColorAndroid='transparent'

          style={styles.TextInputStyleClass}

        />

 <TextInput

     
          placeholder="Enter Password"

         
           onChange={this.onChange}
       
          underlineColorAndroid='transparent'

          style={styles.TextInputStyleClass}
          secureTextEntry={true}

        />

I add a friend of the console output of my code, user: 1 , password:123´

my Out

enter image description here

Upvotes: 2

Views: 703

Answers (1)

Drew Reese
Drew Reese

Reputation: 202836

Issue

  1. The onChange event doesn't have a name property to destructure from event.target. name is undefined and resolves to the third key "".
  2. React state updates are asynchronous, so you can't console log the updated state in the same render cycle the update is enqueued in. Notice all your console logs are a "cycle" behind the onChange event.

Solution

Restructure your onChange callback be a curried function. Attach to the onChangeText prop so the text value is passed, and provide a "name" value for the TextInput that matches the state it is updating.

onChange = name => value => {
  this.setState({ [name]: value });
}

...

<TextInput
  placeholder="Enter User Name"  
  onChangeText={this.onChange('UserName')}
  underlineColorAndroid='transparent'
  style={styles.TextInputStyleClass}
/>

To log the updated state use the componentDidUpdate lifecycle method.

componentDidUpdate() {
  console.log(this.state);
}

Upvotes: 1

Related Questions