javascript - 使用 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
?
谢谢
解决方案
因此,在这种情况下,您需要有一个复选框组和复选框组件。检查以下代码段。感谢这个包。
出于您的目的,您可以安装包并使用,这样包的大小会更小。
为了更好地理解,添加了一个 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;
工作冷凝箱
推荐阅读
- javascript - Javascript fetch() 没有从本地主机返回预期的 json
- java - 在 Netty 上,如何在客户端(Boostrap)连接上使用相同的 ServerBootstrap IP/PORT?
- ascii - 字符串的 ASCII 值
- javascript - React-有条件地渲染较大的组件还是较小的子组件更好
- linux-kernel - 内核抢占和禁用中断的内嵌汇编代码是什么?
- android - 在 Docker 中为 Android 运行并行 Gitlab CI 作业
- python - 如何解决未满足的依赖项错误?
- python - 在 Python IDLE 中工作但不在 VSCode 中的代码?
- c++ - 错误:使用类模板“地图”需要模板参数 (C++)
- microsoft-graph-api - 向多租户应用添加权限后更新范围