antd selectTree实现带全选框的选择器
import React, { useState } from "react";
import { TreeSelect,Checkbox} from "antd";
import "./index.less";
import {clone} from 'lodash'
const { TreeNode } = TreeSelect;
const { SHOW_CHILD } = TreeSelect;
const treeData = [
// {
// title: "全部",
// value: "0",
// key: "0",
// state: true,
// isLeaf:true,
// },
{
title: "Node1",
value: "1",
key: "1",
state: true,
},
{
title: "Node2",
value: "2",
key: "2",
state: true,
},
{
title: "Node3",
value: "3",
key: "3",
state: true,
},
];
const Summary = () => {
const [value, setValue] = useState([]);
const [selectAnalyseType, setSelectAnalyseType] = useState([]);
const [checkAll, setCheckAll] = useState(false);
const [indeterminate, setIndeterminate] = useState(false);
const onChange = (
newValue,
label,
extra
) => {
//preSelectAll:上一次是否全选
const preSelectAll = extra.preValue?.map((v) => v.value).includes("0");
// 上一次没有全选,这次全选了=》全选
if (!preSelectAll && newValue.includes("0")) {
setValue(treeData.map((v) => v.value));
return;
}
// 已经选择的有全选,点击选项=》取消全选选项且选择选项
else if (newValue.length > 1 && newValue.includes("0")) {
setValue(newValue.filter((v) => v !== "0"));
}
// 上一次全选,这次取消全选=》全部反选
else if (preSelectAll && !newValue.includes("0")) {
setValue([]);
}
// 没有选择全选选项,但是选择了别的所有选项=》选择全部选项(包括全选)
else if (
newValue.length === treeData.length - 1 &&
!newValue.includes("0")
) {
setValue(treeData.map((v) => v.value));
}
//正常选择
else {
setValue(newValue);
}
};
const onSelectChange=(e)=>{
console.log(e)
setSelectAnalyseType(e);
setIndeterminate(!!e.length && e.length < 4);
setCheckAll(e.length === 4);
}
const tProps = {
// treeData,
value:selectAnalyseType,
onChange:onSelectChange,
treeCheckable: true,
showCheckedStrategy: SHOW_CHILD,
placeholder: "Please select",
style: {
width: "100%",
},
placement:'bottomRight',
dropdownRender:(menu) => {
return <>
<div className="ant-select-tree">
<div className="ant-select-tree-list">
<div className="ant-select-tree-list-holder">
<div className="ant-select-tree-list-holder-inner">
<div className="ant-select-tree-treenode ant-select-tree-treenode-switcher-close"
onClick={()=>{
const _val = clone(selectAnalyseType);
console.log('_val',_val)
setSelectAnalyseType(_val.length < 4 ? [0,1,2,3] : []);
setIndeterminate(false);
setCheckAll(_val.length < 4);
}}>
<span className="ant-select-tree-switcher ant-select-tree-switcher-noop"></span>
<Checkbox style={{'z-index':99}}
checked={checkAll}
indeterminate={indeterminate}
// className="ant-select-tree-checkbox"
className="check-box"
/>
<span className="ant-select-tree-node-content-wrapper ant-select-tree-node-content-wrapper-normal">
<span className="ant-select-tree-title"> face</span>
</span>
</div>
</div>
</div>
</div>
</div>
{menu}
</>
}
};
return<TreeSelect {...tProps} >
{
['face','person','vehicle','novihecle'].map((item,index)=>{
return (
<TreeNode value={index} label={item} title={item}/>
)
})
}
</TreeSelect>;
};
export default Summary;