[英]Toggling dynamically created checkbox in react
I have created a table dynamically in react with some fields and a checkbox in each row. 我已经动态地创建了一个表,与一些字段和每行中的复选框做出反应。 Now In the column header I have a checkbox.
现在在列标题中我有一个复选框。 When I click the checkbox I want all the rows checkbox to be selected.
当我单击复选框时,我想要选中所有行复选框。 Also now if I click any checkbox, that should toggle its state.
此外,如果我单击任何复选框,那么应切换其状态。
Till now I am able to generate the dynamic rows in the table and delete individual rows. 直到现在我能够在表中生成动态行并删除单个行。
Table Headers 表头
<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>
Function to add new user 添加新用户的功能
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])});
}
CheckAllfunction: CheckAllfunction:
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
}
}
}
one possible way I find is to associate a checked state property with each of the checkboxes that I create but it will be difficult to manage, since I will be performing CRUD operations on the rows. 我找到的一种可能的方法是将已检查的状态属性与我创建的每个复选框相关联,但是很难管理,因为我将对行执行CRUD操作。
Thanks for help in advance 提前感谢您的帮助
Checkboxes are about toggling data state of variable which is limited to true/false value. 复选框是关于切换变量的数据状态,其限制为真/假值。 There is no need to read it's value from DOM, React offers you much cleaner way.
没有必要从DOM读取它的价值,React为您提供更清洁的方式。
toggleCheckbox() {
checkbox.checked = !checkbox.checked;
}
Please, see this fiddle . 拜托,请看这个小提琴 。 It contains full example with code handling your use case on data level.
它包含完整的示例,其中包含处理数据级用例的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.