我创建了动态生成的输入文本字段,但无法找到一种方法来读取和获取值并将其存储到数组中。请在下面找到代码
我有单独的组件用于添加新的输入字段行,称为 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;
此外,我有主要组件调用 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>
);
}
}
我需要读取每个生成的文本字段值并将其存储到数组中
最佳答案
您的代码示例似乎不完整 - 您甚至没有将值添加到您的行中 所以这里只有一个简短的答案:
检查 react 引用 https://facebook.github.io/react/docs/more-about-refs.html
您可以为您的每一行添加一个 ref
let rows = this.state.rows.map(row => {
return <Row />
});
也许更好的解决方案是向您的行添加一个 onChange 监听器并更新您的父组件的状态
let rows = this.state.rows.map((row,i) => {
return <Row ref={'row-'+i} onChange={(event) => this.myListener(event,i)} />
});
关于javascript - React 从动态添加的输入文本字段中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36338259/