[英]Toggling dynamically created checkbox in react
我已經動態地創建了一個表,與一些字段和每行中的復選框做出反應。 現在在列標題中我有一個復選框。 當我單擊復選框時,我想要選中所有行復選框。 此外,如果我單擊任何復選框,那么應切換其狀態。
直到現在我能夠在表中生成動態行並刪除單個行。
表頭
<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])});
}
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
}
}
}
我找到的一種可能的方法是將已檢查的狀態屬性與我創建的每個復選框相關聯,但是很難管理,因為我將對行執行CRUD操作。
提前感謝您的幫助
復選框是關於切換變量的數據狀態,其限制為真/假值。 沒有必要從DOM讀取它的價值,React為您提供更清潔的方式。
toggleCheckbox() {
checkbox.checked = !checkbox.checked;
}
拜托,請看這個小提琴 。 它包含完整的示例,其中包含處理數據級用例的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.