我创建了一个ReactJs页面,允许管理员将用户添加到平台。现在,管理员在提交表单之前可以添加尽可能多的用户。默认情况下,显示包含输入字段的一个表格行,然后点击添加按钮后,会添加新行,管理员可以填写必要的详细信息。
我想为每一行的输入字段添加onChange事件。由于这是相当动态的,所以不知道如何做。随着添加新行,状态将不得不改变。不知道如何更新此状态并为每个行中的每个字段添加onChange事件。以下是我的现有代码:
我想为每一行的输入字段添加onChange事件。由于这是相当动态的,所以不知道如何做。随着添加新行,状态将不得不改变。不知道如何更新此状态并为每个行中的每个字段添加onChange事件。以下是我的现有代码:
export default class Admins extends React.Component{
constructor(props){
super(props);
this.state = {
errors : '',
success : '',
rows : [1]
}
this.addRow = this.addRow.bind(this);
this.fetchRows = this.fetchRows.bind(this);
this.removeRow = this.removeRow.bind(this);
}
addRow(){
var last = this.state.rows[this.state.rows.length-1];
var current = last + 1;
this.setState({
rows : this.state.rows.concat(current)
});
}
removeRow(index){
var array = this.state.rows;
array.splice(index, 1)
this.setState({
rows : array
})
}
fetchRows(){
return this.state.rows.map((row, index) => (
//console.log(row, index)
<tr key={row}>
<td className="text-center">
<button type="button" onClick={(e)=> this.removeRow(index)} data-toggle="tooltip" className="btn btn-xs btn-danger"
data-original-title=""><i className="fa fa-trash"></i>
</button>
</td>
<td>
<input type="text" className="form-control" onChange={}/>
</td>
<td>
<input type="text" className="form-control" onChange={}/>
</td>
<td>
<input type="text" className="form-control" onChange={}/>
</td>
</tr>
));
}
render(){
return(
<div>
<Top/>
<SideBar/>
<div className="breadcrumb-holder">
<div className="container-fluid">
<ul className="breadcrumb">
<li className="breadcrumb-item"><Link to="/">Dashboard</Link></li>
<li className="breadcrumb-item active">Admins</li>
</ul>
</div>
</div>
<section className="forms">
<div className="container-fluid">
<header>
<h3 className="h5 display">Admins</h3>
</header>
<div className="row">
<div className="col-lg-6">
<h5 className="text-danger">{this.state.errors}</h5>
<h5 className="text-success">{this.state.success}</h5>
</div>
</div>
<div className="row">
<div className="col-lg-6">
<div className="card">
<div className="card-header d-flex align-items-center">
<h5></h5>
</div>
<div className="card-body">
<table className="table table-bordered">
<thead>
<tr>
<th width="5%">Actions</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
{this.fetchRows()}
<tr>
<td className="text-center">
<button type="button" onClick={this.addRow} data-toggle="tooltip" className="btn btn-xs btn-primary"
data-original-title=""><i className="fa fa-plus"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
);
}
}
removeRow()
中,你将array
变量设置为this.state.rows
,但这并不会创建一个新的数组,而是创建了对该数组的引用。因此,在下一行调用splice()
(它会改变调用它的数组),这实际上会改变状态本身。使用slice()
来复制状态数组,例如let currentRows = this.state.rows.slice(0)
。另外,不要把变量命名为'array'之类的东西,给它们有意义的名称。 - Jayce444