繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM