【发布时间】:2016-08-24 10:46:10
【问题描述】:
我已经动态地创建了一个表格,以对每行中的一些字段和一个复选框做出反应。现在在列标题中我有一个复选框。当我单击复选框时,我希望选中所有行复选框。现在,如果我单击任何复选框,它应该会切换其状态。
到目前为止,我能够在表中生成动态行并删除单个行。
表格标题
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table id="mytable" class="table table-bordred table-striped">
<thead>
<th><input type="checkbox" id="checkall" onChange={this.checkAll}/></th>
<th>Id</th>
<th>Id1</th>
<th>Id2</th>
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</thead>
<tbody>{users}</tbody>
</table>
</div>
</div>
</div>
新增用户功能
addUserState =(dat) => {
let data = JSON.parse(dat);
let id = this.randomPassword(32);
let newElement = null
newElement = <tr>
<td><input type="checkbox" class="checkthis"/></td>
<td class="userId">{id}</td>
<td class="id1">{data.payload.id1}</td>
<td class="id2">{data.payload.id2}</td>
<td class="userEmail">{data.payload.email}</td>
<td><p data-placement="top" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>
<td><p data-placement="top" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" onClick={this.deleteUser.bind(this, id)}><span class="glyphicon glyphicon-trash"></span></button></p></td>
</tr>
this.setState({users: this.state.users.concat([newElement])});
}
CheckAll 函数:
checkAll = (e) => {
let length = this.state.users.length;
if(e.target.checked) {
for(let i = 0; i < length; i++) {
console.log(this.state.users[i]);
//Do what here
}
}
}
我发现的一种可能方法是将 checked state 属性与我创建的每个复选框相关联,但这将难以管理,因为我将执行 CRUD 对行的操作。
提前感谢您的帮助
【问题讨论】:
-
您需要为表格行创建新的反应组件并在这个新组件中处理状态。在这种情况下,您将能够通知所有需要检查的组件行。此外,您将能够获得行的状态。
标签: javascript checkbox reactjs