如何在React中选中/取消选中复选框列表 [英] How to check/uncheck a list of checkboxes in react

查看:84
本文介绍了如何在React中选中/取消选中复选框列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 room 页面,并且在该页面中有一个与该房间相连的传感器列表,可以使用复选框来选择这些传感器,如下所示:

I have a room page and in that page I have a list of sensors attached to that room, those sensors can be selected using a checkbox, like so:

<div className="checkboxRowContent">
  {sensors.map(s => {
    return (
      <div className="checkboxElementWrapper" key={s.id}>
        <label htmlFor={`sensor${s.id}`}>
          <div className="checkboxLabel">
            <Link to={`/sensors/edit/${s.id}`}>{s.name}</Link>
          </div>
          <input
            type="checkbox"
            id={`sensor${s.id}`}
            name="sensorId"
            value={s.id}
            checked={s.roomId === values.id}
            onChange={handleCheckbox}
          />
          <span className="checkbox" />
        </label>
      </div>
    );
  })}
</div>

问题是-这种方法禁止我取消选中该复选框(因此,如果在db中该传感器连接到该房间,就是这样).我该如何重写它,以便可以选中/取消选中此复选框?

the problem is - this approach prohibits me from unchecking the checkbox (so if in db that sensor is attached to that room - that's it). How could I rewrite this so that I can check/uncheck this checkbox?

推荐答案

在该类中,您必须具有状态,

in the class you must have state for that,

一个样本有点像这样

export default class yourComponent extends React.Component {

  state = {
    checkedBoxes: []
  }

  handleCheckbox = (e, s) => {
    const checkedBoxes = [...this.state.checkedBoxes];
    if(e.target.checked) {
      checkedBoxes.push(s)
    } else {
      const index = checkedBoxes.findIndex((ch) => ch.roomId === s.roomId);
      checkedBoxes.splice(index, 1);
    }
    this.setState({checkedBoxes});
  }


  render() {

    return(
      <div className="checkboxRowContent">
      {sensors.map(s => {
          return (
            <div className="checkboxElementWrapper" key={s.id}>
              <label htmlFor={`sensor${s.id}`}>
                <div className="checkboxLabel">
                  <Link to={`/sensors/edit/${s.id}`}>{s.name}</Link>
                </div>
                <input
                  type="checkbox"
                  id={`sensor${s.id}`}
                  name="sensorId"
                  checked={checkedBoxes.find((ch) => ch.roomId === s.roomId)}
                  onChange={(e) => handleCheckbox(e, s)}
                />
                <span className="checkbox" />
              </label>
            </div>
          );
        })}
      </div>
    )
  }
}

状态, checkedBoxes ,用于获取所有选中的复选框.

A state, checkedBoxes for getting all selected checkboxes.

用于处理复选框点击的处理程序 handleCheckbox

A handler handleCheckbox for handling checkbox clicks,

这篇关于如何在React中选中/取消选中复选框列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆