如何在React Native中获取TextInput更改事件的目标?

时间:2018-07-02 18:20:43

标签: reactjs react-native

我有一系列TextInput组件,这些组件是根据映射中的条目数动态生成的。我试图分别为每个TextInput设置状态,但无法完全弄清楚。这是我的代码:

<View style={{ flex: 1 }}>
                <ScrollView contentContainerStyle={{ paddingVertical: 20 }}>
                    {ostDataPoints.map(({ ostDPID, ostDPName, ostDPUOM }) => (
                        <Card title={`${ostDPName}(${ostDPUOM})`} key={ostDPID} >
                            <Text style={{ marginBottom: 10 }}>
                                Test Name: {ostDPID}
                            </Text>
                            <Text style={{ marginBottom: 10 }}>
                                Test Type: {ostDPUOM}
                            </Text>
                            <TextInput
                                style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                                onChangeText={(text) => this.setState({ text })}
                                value={this.state.text}
                            />
                            <Button
                                backgroundColor="#03A9F4"
                                title="VIEW NOW"
                                onPress={() => {
                                    alert("hi");
                                }}
                            />
                        </Card>
                    ))}
                </ScrollView>
            </View>

我想做这样的事情(通过反应):

handleTextChange = (event) => {
        this.setState({
            [event.target.name]: event.target.value
        })
    }

有没有办法在react native中设置event.target.name值?

1 个答案:

答案 0 :(得分:1)

您可以使用ID或名称props来标识正在更改的输入。以下代码为例:

CodeSandbox

index.js

import React from "react";
import ReactDOM from "react-dom";
import MyInput from "./MyInput";

import "./styles.css";

const items = [{ name: "first" }, { name: "second" }, { name: "third" }];

class App extends React.Component {
  onTextChange(id, value) {
    console.log(id, value);
  }

  render() {
    return (
      <ul>
        {items.map(item => (
          <li>
            <MyInput
              name={item.name}
              textChange={(id, value) => this.onTextChange(id, value)}
            />
          </li>
        ))}
      </ul>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

MyInput.js

import React from "react";

export default class MyInput extends React.Component {
  textChange(event) {
    this.props.textChange(this.props.name, event.target.value);
  }

  render() {
    return (
      <input
        type="text"
        name={this.props.name}
        onChange={e => this.textChange(e)}
        {...this.props}
      />
    );
  }
}