目录: 1、 注意事项 2、效果图 3、代码
-------------------------------
注意事项:
关系:
<Checkbox onChange={onCheckAllChange} > </Checkbox>
<CheckboxGroup value={checkedList}>
<Checkbox > </Checkbox>
<CheckboxGroup><Checkbox > </Checkbox>×2</CheckboxGroup>
<Checkbox > </Checkbox>
<Checkbox > </Checkbox>
</CheckboxGroup>
1、 <Checkbox > </Checkbox> 是如何控制 <CheckboxGroup>
答:通过 onChange={onCheckAllChange} 属性监听点击,回调函数,然后设置<CheckboxGroup>的
value属性 。
2、子 <Checkbox > 被点满后,最外层<Checkbox >如何变为亮
答: 通过<CheckboxGroup> onchang属性监听子 <Checkbox >是否被点满吗,如果点满,就设置最外层的 <Checkbox > 的 checked 为true
3、被<CheckboxGroup>包裹的<Checkbox >,它的checked属性会失效。
4、具体看下代码,最重要是搞清楚 CheckboxGroup 是如何控制它的子 <Checkbox > 值的? 同时,最外层<Checkbox > 是如何控制 <CheckboxGroup>的?
--------------------------
效果图:
--------------------------
import React, { useState } from "react";
import { Checkbox, Divider } from "antd";
const CheckboxGroup = Checkbox.Group;
const plainOptions = ["Apple", "Pear", "Orange"];
const defaultCheckedList = ["Apple", "Orange"];
const App = () => {
const [checkedList, setCheckedList] = useState([]);
const [checkedList1, setCheckedList1] = useState([]);
const [indeterminate, setIndeterminate] = useState(true);
const [checkAll, setCheckAll] = useState(false);
const [checkAll1, setCheckAll1] = useState(false);
const onChange = (list) => {
setCheckedList(list);
setIndeterminate(!!list.length && list.length < plainOptions.length);
setCheckAll(list.length === plainOptions.length);
};
const onChange1 = (list) => {
setCheckedList1(list);
// setCheckAll1(list.length === 2);
if (list.length === 2) {
setCheckedList(Object.assign(checkedList, ["Apple"]));
} else {
let removedArr = checkedList.filter((x) => x !== "Apple");
setCheckedList(removedArr);
}
};
const aaa = (e) => {
console.log(e, "9999999999999");
setCheckedList1(e.target.checked ? ["ee", "ff"] : []);
};
const onCheckAllChange = (e) => {
setCheckedList(e.target.checked ? plainOptions : []);
setIndeterminate(false);
setCheckAll(e.target.checked);
setCheckedList1(e.target.checked ? ["ee", "ff"] : []);
};
return (
<>
<Checkbox
indeterminate={indeterminate}
onChange={onCheckAllChange}
checked={checkAll}
>
最外层全选
</Checkbox>
<Divider />
<CheckboxGroup
// options={plainOptions}
value={checkedList}
onChange={onChange}
>
<Checkbox value="Apple" onChange={aaa}>
aa选项全选
</Checkbox>
<CheckboxGroup
style={{ display: "inline", margin: "5" }}
value={checkedList1}
onChange={onChange1}
>
<Checkbox value="ee">我是被aa包裹的ee</Checkbox>
<Checkbox value="ff">我是被aa包裹的ff</Checkbox>
</CheckboxGroup>
<Checkbox value="Pear" style={{ display: "block" }}>
bb
</Checkbox>
<Checkbox value="Orange">cc</Checkbox>
</CheckboxGroup>
</>
);
};
export default App;