我动态创建了一个表,以响应每行中的一些字段和一个复选框。现在在列标题中我有一个复选框。当我单击复选框时,我希望选中所有行复选框。另外,现在如果我点击任何复选框,应该会切换其状态。
到目前为止,我能够在表中生成动态行并删除单个行。
表格标题
<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 对行的操作。
提前感谢您的帮助
最佳答案
复选框用于切换变量的数据状态,仅限于真/假值。无需从 DOM 中读取它的值,React 为您提供了更简洁的方法。
toggleCheckbox() {
checkbox.checked = !checkbox.checked;
}
请看这个fiddle .它包含完整示例以及在数据级别处理您的用例的代码。
关于javascript - 在 react 中切换动态创建的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36935522/