loadData 动态加载选项,无法与 showSearch 一起使用
isLeaf: false 时会强制标记为父节点,即使当前节点没有 children,也会显示展开图标
image.png

loadData 案例
https://ant-design.antgroup.com/components/cascader-cn#cascader-demo-lazy

AntdCascader loadData

  1. import React, { useState, useEffect } from 'react';
  2. import { Cascader } from 'antd';
  3. import { useRequest } from 'ahooks';
  4. import { isEqual, noop } from 'lodash-es'
  5. interface IProps {
  6. value?: string | string[];
  7. onChange?: () => void;
  8. request: () => Promise<void>;
  9. requestChildren: () => Promise<void>;
  10. dependencies?: object;
  11. requestOptions?: object;
  12. placeholder?: string;
  13. dataKey?: string;
  14. }
  15. function AntdCascader(props: IProps) {
  16. const {
  17. value,
  18. onChange = noop,
  19. dependencies,
  20. request,
  21. requestOptions,
  22. requestChildren,
  23. dataKey,
  24. placeholder = '请选择',
  25. ...rest
  26. } = props;
  27. const [selected, setSelected] = useState([]);
  28. const [options, setOptions] = useState([]);
  29. const $init = useRequest(request, requestOptions);
  30. const $children = useRequest(requestChildren, requestOptions);
  31. useEffect(() => {
  32. init();
  33. }, [dependencies, dataKey]);
  34. // update
  35. useEffect(() => {
  36. if (isEqual(value, selected)) return;
  37. setSelected(value);
  38. }, [value]);
  39. async function init() {
  40. const res = await $init.runAsync(dependencies);
  41. const result = dataKey ? res[dataKey] : res;
  42. // isLeaf: false 强制标记为父节点
  43. const _options = result.map(it => ({...it, isLeaf: false}))
  44. setOptions(result);
  45. }
  46. function handleChange(values) {
  47. setSelected(values);
  48. onChange(values);
  49. }
  50. // 动态加载选项,无法与 showSearch 一起使用
  51. async function loadData(selectedOptions) {
  52. const targetOption = selectedOptions.at(-1);
  53. targetOption.loading = true;
  54. const res = await $children.runAsync(targetOption.value);
  55. const result = dataKey ? res[dataKey] : res;
  56. Object.assign(targetOption, {
  57. loading: false,
  58. children: result,
  59. });
  60. setOptions([...options]);
  61. }
  62. return (
  63. <Cascader
  64. // fieldNames
  65. changeOnSelect
  66. {...rest}
  67. options={options}
  68. value={selected}
  69. onChange={handleChange}
  70. loadData={loadData}
  71. placeholder={placeholder}
  72. />
  73. );
  74. }
  75. export default AntdCascader;