简体   繁体   English

如何在反应js中获取具有相同属性名称的数组中输入标签的值

[英]how to get value of input tag in array with same attribute name in react js

i want to get value of first input tag in eduction [0] and value of second input tag in education[1] education is array.我想获得教育[0]中第一个输入标签的值,教育[1]中第二个输入标签的值教育是数组。

<input  type="text" name="education" value={this.state.education[0]} onChange={this.handleChange}  
class="form-control"  />
<input type="text"  name="education" value={this.state.education[1]} onChange={ 
this.handleChange()} class="form-control"/>

It's better to do it as follow (It allow you to dynamically create your inputs and also if you don't want dynamic input you can use the same technique as well)最好按照以下方式进行(它允许您动态创建输入,如果您不想要动态输入,您也可以使用相同的技术)

constructor(props) {
    super(props);
    this.state = {
      education: ["", ""] // I've added 2 items to create 2 inputs
    };
    this.handleChange = this.handleChange.bind(this);
  }

handleChange(e) {
    const education = [...this.state.education];
    education[e.target.id] = e.target.value;
    this.setState({
      education: education
    });
  }

render() {
    return (
      <div>
        {
          this.state.education.map((item, index) => (
          <input
            id={index}
            type="text"
            name="education"
            value={this.state.education[index]}
            onChange={this.handleChange}
            class="form-control"
          />
        ))
        }
      </div>
    );
}

In your second input you (by mistake i think) added () after your this.handleChange function.在您的第二个输入中,您(我认为是错误的)在this.handleChange function 之后添加了() This means this function will be called immediately and won't be called onChange.这意味着这个 function 将被立即调用,不会被调用 onChange。

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

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