如何在一个处理程序中处理多个更改事件?

时间:2017-04-15 18:35:44

标签: javascript reactjs onchange

我在视图中正在侦听三个输入的onChangeText。但不是使用三个单独的onChangeText处理程序。我想将输入的输入状态名称传递给处理程序,并让它从中设置状态。

我尝试了这个例子,但e.target.value返回undefined。传递name作为第二个参数,e作为指向元素的指针:

import React, { Component } from 'react';
import { View, StyleSheet, Alert, Image, TextInput } from 'react-native';
import { Constants } from 'expo';

export default class App extends Component {
  state = {
    setValue: 0,
    travelValue: 0,
    runValue: 0

  };


  _handleTextChange (e, name) {
      var change = {};
      change[name] = e.target.value;
      this.setState(change);
  }


  render() {
    return (
      <View style={styles.container}>


        <TextInput
          value={this.state.setValue}
          keyboardType = 'numeric'
          onChangeText={this._handleTextChange.bind(this, 'setValue')}
          style={{ width: 200, height: 44, padding: 8 }}
        />
         <TextInput
          value={this.state.travelValue}
          keyboardType = 'numeric'
          onChangeText={this._handleTextChange.bind(this, 'travelValue')}
          style={{ width: 200, height: 44, padding: 8 }}
        />
         <TextInput
          value={this.state.runValue}
          keyboardType = 'numeric'
          onChangeText={this._handleTextChange.bind(this, 'runValue')}
          style={{ width: 200, height: 44, padding: 8 }}
        />

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingTop: Constants.statusBarHeight,
    paddingBottom: '20%',
    backgroundColor: '#ecf0f1',
  },
});

问题:

如何在一个处理程序中处理多个更改事件?

1 个答案:

答案 0 :(得分:1)

因为您使用的顺序错误,请使用它:

_handleTextChange (name, e) {  //first name then event
    var change = {};
    change[name] = e.target.value;
    this.setState(change);
}

您也可以这样写,向Input元素定义name属性,然后name访问e.target.name,如下所示:

<TextInput
    value={this.state.setValue}
    name='setValue'
    onChangeText={this._handleTextChange}
    ....

Bind _handleTextChange function中的constructor

this._handleTextChange = this._handleTextChange.bind(this);

像这样使用_handleTextChange

_handleTextChange(e){
      var change = {};
      change[e.target.name] = e.target.value;
      this.setState(change);
}