切换多个复选框无法在react

时间:2019-07-03 09:51:02

标签: javascript reactjs checkbox

如何在反应中切换我的复选框?

我为此创建了一个onChange事件处理程序,但是它不起作用。

我用于创建复选框的代码:

(this.state.allemployees.map((employee) =>
  <tr key={employee.empmainid}>
    <td>{employee.empname}</td>
    <td>{employee.empid}</td>
    <td><input onChange={this.handleCheckbox} getUsername={employee.empname} className="" type="checkbox" name={employee.empmainid} value={employee.empmainid} checked={this.state.employeeIdInArray.includes(employee.empmainid) ? true : false} /></td>
  </tr>
))

我在构造函数中定义了this.handleCheckbox = this.handleCheckbox.bind(this)

我用于处理复选框的代码:

handleCheckbox(event) {
  var allemployyes2 = this.state.allemployyes2;
  const { value, checked } = event.target;  // get id and checked status
  var allemployyes1 = this.state.allemployyes1;

  // Add to an array if checked and remove - if uncheck
  if (checked) {
    var username_push = event.target.getAttribute("getUsername");
    allemployyes1.push(value);
    allemployyes2.push(username_push);
  } else {
    allemployyes1 = allemployyes1.filter(id => id !== value);
  }

  this.setState({ allemployyes1: allemployyes1, allemployyes2: allemployyes2 });
    console.log(this.state.allemployyes2);
  }

0 个答案:

没有答案