简体   繁体   English

如何制作回调函数来填充 textinput onChangeText 的值道具

[英]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.在这段代码中,我试图实现的是在 Textinput 的 value 属性中获取类型化的值。 However, what I get is null.但是,我得到的是空的。 A setState is asynchronous, I'm lagging one step behind. setState是异步的,我落后了一步。 I am new in react, and I do not know how I can make a callback function that can give me the current value.我是 React 新手,我不知道如何制作一个可以给我当前值的回调函数。

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) (我对 e.target.value 没有信心,如果它是 null 或 undefined,传递 e.target 并记录它,看看你能从中得到什么值)

then change your function with the following然后使用以下更改您的功能

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

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

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