loadData 动态加载选项,无法与 showSearch 一起使用
isLeaf: false 时会强制标记为父节点,即使当前节点没有 children,也会显示展开图标
loadData 案例
https://ant-design.antgroup.com/components/cascader-cn#cascader-demo-lazy
AntdCascader loadData
import React, { useState, useEffect } from 'react';
import { Cascader } from 'antd';
import { useRequest } from 'ahooks';
import { isEqual, noop } from 'lodash-es'
interface IProps {
value?: string | string[];
onChange?: () => void;
request: () => Promise<void>;
requestChildren: () => Promise<void>;
dependencies?: object;
requestOptions?: object;
placeholder?: string;
dataKey?: string;
}
function AntdCascader(props: IProps) {
const {
value,
onChange = noop,
dependencies,
request,
requestOptions,
requestChildren,
dataKey,
placeholder = '请选择',
...rest
} = props;
const [selected, setSelected] = useState([]);
const [options, setOptions] = useState([]);
const $init = useRequest(request, requestOptions);
const $children = useRequest(requestChildren, requestOptions);
useEffect(() => {
init();
}, [dependencies, dataKey]);
// update
useEffect(() => {
if (isEqual(value, selected)) return;
setSelected(value);
}, [value]);
async function init() {
const res = await $init.runAsync(dependencies);
const result = dataKey ? res[dataKey] : res;
// isLeaf: false 强制标记为父节点
const _options = result.map(it => ({...it, isLeaf: false}))
setOptions(result);
}
function handleChange(values) {
setSelected(values);
onChange(values);
}
// 动态加载选项,无法与 showSearch 一起使用
async function loadData(selectedOptions) {
const targetOption = selectedOptions.at(-1);
targetOption.loading = true;
const res = await $children.runAsync(targetOption.value);
const result = dataKey ? res[dataKey] : res;
Object.assign(targetOption, {
loading: false,
children: result,
});
setOptions([...options]);
}
return (
<Cascader
// fieldNames
changeOnSelect
{...rest}
options={options}
value={selected}
onChange={handleChange}
loadData={loadData}
placeholder={placeholder}
/>
);
}
export default AntdCascader;