在react中切换动态创建的复选框

Toggling dynamically created checkbox in react

本文关键字:创建 复选框 动态 react      更新时间:2023-09-26

我在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
            }
        }
    }

我发现的一种可能的方法是将checkedstate属性与我创建的每个复选框相关联,但这将很难管理,因为我将对行执行CRUD操作。

感谢您提前提供帮助

复选框是关于切换变量的数据状态的,该状态仅限于true/false值。不需要从DOM中读取它的值,React为您提供了更干净的方式。

toggleCheckbox() {
  checkbox.checked = !checkbox.checked;
}

请看这把小提琴。它包含了在数据级别处理用例的完整示例。