简体   繁体   English

从动态添加的输入文本字段中获取值

[英]React get values from dynamically added inputs text fields

I have created dynamically generate input text-fields but unable to find a way to read and get the values and stored it to an array. 我创建了动态生成输入文本字段但无法找到读取和获取值并将其存储到数组的方法。 please find the code below 请找到下面的代码

i have separate component for add new input field rows called IncrementTableRow 我有单独的组件用于添加名为IncrementTableRow的新输入字段行

import React, {PropTypes} from 'react';

class IncrementTableRow extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <tr>
        <th scope="row">{this.props.index}</th>
        <td><input type="text" className="form-control" ref={"firstValue"+this.props.index} placeholder=""/></td>
        <td><input type="text" className="form-control" ref={"secondValue"+this.props.index} placeholder=""/></td>
      </tr>
    );
  }
}

export default IncrementTableRow;

also, i have main component to call IncrementTableRow below is the calling line. 另外,我有调用IncrementTableRow的主要组件是调用线。

export default class SuggestInterestProductDetails extends Component {

constructor(props) {
    super(props);
    this.state = {
      rows: []
    };
    this.AddRow = this.AddRow.bind(this);
  }

AddRow() {
    this.setState({
      rows: [{val: 5}, ...this.state.rows]
    });
  }

  render() {
    let rows = this.state.rows.map(row => {
      return <Row />
    });

    return (
    <div>
      <button onClick={this.AddRow}>Add Row</button>
      <table>
        {rows}
      </table>
    </div>
    );
  }


}

i need to read each and every generated text field values and stored it to an array 我需要读取每个生成的文本字段值并将其存储到数组中

your code example seems incomplete - you dont even add the values to your rows so here only a short answer: 你的代码示例似乎不完整 - 你甚至都没有将值添加到行中,所以这里只是一个简短的答案:

check react refs https://facebook.github.io/react/docs/more-about-refs.html check react refs https://facebook.github.io/react/docs/more-about-refs.html

you can add a ref to each row in your 你可以在你的每一行添加一个引用

let rows = this.state.rows.map(row => {
  return <Row />
});

maybe an even better solution would be to add an onChange listener to your rows and update the state of your parrent component 也许更好的解决方案是在你的行中添加一个onChange监听器并更新你的parrent组件的状态

let rows = this.state.rows.map((row,i) => {
  return <Row ref={'row-'+i} onChange={(event) => this.myListener(event,i)} />
});

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

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