简体   繁体   中英

TextInput OnChange in React native

Please help me. I have a TextInput , my problem is when I type the numeric value, that value going to multiply with some number. When I type 1000 , this will get saved to state as 1000 , but it saves to store as 100 . The results differ.

 <TextInput
  onChangeText={this.handle_bill_Amount}
  style={styles.input} 
  placeholder="Amount"
  value={this.state.Amount}
  keyboardType = 'numeric'
  enablesReturnKeyAutomatically={true}
  placeholderTextColor = "#824242"
  underlineColorAndroid="transparent">
 </TextInput>


  handle_bill_Amount = Amount => {
  this.setState({ Amount})
  let billamt = this.state.Amount;
  console.log(billamt);
  }

 constructor(props) {
    super(props);
    this.state = {
    Amount: '',
    }
    this.handle_bill_Amount = this.handle_bill_Amount.bind(this);
}

Guys help me please!

this.setState is async in nature, hence non-deterministic in the next statement. So, when you are logging the value, state might not yet have the updated value. So for deterministic behavior, it is advised that you use the second argument, which is a callback, to get the correct state. It is invoked when setState is executed.

this.setState({Amount}, () => console.log(this.state.Amount))

I think results are not different, it's just your console.log which confuses you. It will print out 100 instead of 1000 because your are doing console log inside the function which is setting the new state. Try to do it somewhere else, eg in componentWillReceiveProps , or componentWillUpdate and you'll see it's ok.

Hope this helps.

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