首页 > 解决方案 > 使用 React 检查主复选框时如何检查子复选框?

问题描述

我想在选中主要复选框时动态检查子复选框。我在 Stackoverflow 上找到了一些解决方案和其他相关帖子,但他们总是使用 JQuery。我想使用 ReactJS 来实现,这是我的代码片段。

ul {
    list-style-type: none;
}
<div>
<input type="checkbox" id="fullbody" />
<label htmlFor="fullbody">Download the points for the full body</label>
<ul>
    <li><input type='checkbox' id="upperbody"/>Download only the upper body points</li>
    <li><input type='checkbox' id="lowerbody" />Download only the lower body points</li>
    <li><input type='checkbox' id="head" />Download only the head points</li>
    <li><input type='checkbox' id="fullhands" />Download both hands points</li>
    <li><input type='checkbox' id="lefthand" />Download left hand points</li>
    <li><input type='checkbox' id="righthand" />Download right hand points</li>
</ul>
</div>

所以我的问题是,如何在选中时动态检查儿童复选框fullbody

谢谢

标签: javascripthtmlreactjscheckbox

解决方案


因此,在这种情况下,您需要有一个复选框组和复选框组件。检查以下代码段。感谢这个

出于您的目的,您可以安装包并使用,这样包的大小会更小。

为了更好地理解,添加了一个 div 来显示单击每个父复选框时的值。

应用程序.js

import React from "react";
import { CheckboxGroup, AllCheckerCheckbox, Checkbox } from "./Checkbox";
import "./styles.css";

const App = () => {
  const [onChange, setOnChange] = React.useState({});

  return (
    <div>
      <CheckboxGroup onChange={setOnChange}>
        <label>
          <AllCheckerCheckbox />
          <span>Download the points for the full body</span>
        </label>
        <ul>
          <li>
            <label>
              <Checkbox name="upperbody" />
              <span>Download only the upper body points</span>
            </label>
          </li>
          <li>
            <label>
              <Checkbox name="lowerbody" />
              <span>Download only the lower body points</span>
            </label>
          </li>
          <li>
            <label>
              <Checkbox name="head" />
              <span>Download only the head points</span>
            </label>
          </li>
          <li>
            <label>
              <Checkbox name="fullhands" />
              <span>Download both hands points</span>
            </label>
          </li>
          <li>
            <label>
              <Checkbox name="lefthand" />
              <span>Download left hand points</span>
            </label>
          </li>
          <li>
            <label>
              <Checkbox name="righthand" />
              <span>Download right hand points</span>
            </label>
          </li>
        </ul>
      </CheckboxGroup>
      <div>
        <h1>Values</h1>
        <pre>{JSON.stringify(onChange, null, 2)}</pre>
      </div>
    </div>
  );
};

export default App;

工作冷凝箱


推荐阅读