简体   繁体   中英

How to make a call back function to populate value prop of textinput onChangeText

In this code all I'm trying to achieve is that I get the typed value inside the value prop of Textinput. However, what I get is null. A setState is asynchronous, I'm lagging one step behind. I am new in react, and I do not know how I can make a callback function that can give me the current value.

I also wish to later use map, and make dynamic form, I appreciate solution that might work for map function as well.

thanks

import React from 'react';
import {
  View,
  TextInput,
} from 'react-native';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      Email: null,
      Password: null,
      Address: null,
    };
  }

  EnterValue = (name) => {
    return (text) => {
      this.setState({
        [name]: text,
        
      });
    };
  };

  render() {
    return (
      <View>
        <TextInput
          placeholder="enter email"
          value={this.state.Email}
          onChangeText={this.EnterValue('Email')}
          style={{ borderWidth: 2, borderColor: 'skyblue', margin: 20 }}
        />

        <TextInput
          placeholder="Password"
          value={this.state.Password}
          onChangeText={this.EnterValue('Password')}
          style={{ borderWidth: 2, borderColor: 'skyblue', margin: 20 }}
        />

        <TextInput
          placeholder="Address"
          value={this.state.Address}
          onChangeText={this.EnterValue('Address')}
          style={{ borderWidth: 2, borderColor: 'skyblue', margin: 20 }}
        />
      </View>
    );
  }
}

I would do something like this

onChangeText={(e) => this.EnterValue(e.target.value, 'Email')}

( I'm not confident with e.target.value, if it's null or undefined, pass e.target and log it, to see what values you can get from it)

then change your function with the following

EnterValue = (value, inputName) => this.setState({ [inputName]: value});

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