antd 级联选择- 多选
- 将选中或者取消的数据维护起来 ===> [ ]
- 在displayRender 中用Tag渲染 ===> displayRender={(label, selectedOptions) => { }
import React from "react";
import PropTypes from "prop-types";
import { get, isEmpty, reduce, includes, filter } from "lodash";
import { Cascader, Tag } from "antd";
const options = [
{
code: 'zhejiang',
name: '浙江',
items: [
{
code: 'hangzhou',
name: '杭州',
},
],
},
{
code: 'jiangsu',
name: '江苏',
items: [
{
code: 'nanjing',
name: '南京',
},
],
},
];
const CascaderMul = ({ value = [], onChange, style }) => {
// 根据数据拿到code的组合
const connectCode = (arr = []) =>
reduce(arr, (ss, vv) => (!ss ? vv.code : `${ss}-${vv.code}`), "");
return (
<div>
<Cascader
style={style}
allowClear={false}
fieldNames={{ label: "name", value: "code", children: "items" }}
options={options}
value={value}
onChange={(v, l) => {
const curCode = connectCode(l); // 将code记录一下
l[l.length - 1].curCode = curCode;
const allCode = reduce(
value,
(ss, vv) => [...ss, get(vv, [vv.length - 1, "curCode"])],
[]
);
// 已有的,不允许再选
if (!includes(allCode || [], curCode)) {
onChange([...value, l]);
}
}}
displayRender={(label, selectedOptions) => {
const l = isEmpty(selectedOptions)
? value
: [...value, selectedOptions];
return (l || []).map((v, i) => (
<Tag
closable
key={get(v, [v.length - 1, "curCode"])}
onClose={() => onChange(filter(value, (vv, ii) => ii !== i))}
>
{get(v, [v.length - 1, "name"])}
</Tag>
));
}}
/>
</div>
);
};
CascaderMul.propTypes = {
value: PropTypes.array,
style: PropTypes.object,
onChange: PropTypes.func.isRequired,
};
CascaderMul.defaultProps = {
style: {},
value: [],
};
export default CascaderMul;
/// 调用
import React, { useEffect, useState } from "react";
import CascaderMul from "./CascaderMul";
export default () =>{
const [val, setVal] = useState([]);
useEffect(() => {
console.log("val:", val);
}, [val]);
return <CascaderMul
value={val}
onChange={(vv) => setVal(vv)}
style={{ width: 300 }}
/>
}