ant-design/components/tree-select/demo/async.md
章鱼 7fd093bd0a
docs: feat components TS demo (#34742)
* docs: add general components TS demo

* docs: add layout components TS demo

* docs: add navigation components TS demo

* docs: add data entry components TS demo

* chore(deps): add types for qs

* docs: add data display TS demo

* docs: add feedback components TS demo

* docs: add other components TS demo

* chore(deps): add types

* docs: unified demo code style

* docs: fix lint error

* docs: add demo TS type

* docs: fix demo TS type

* test: update snapshot

* docs: fix TS demo

* feat: update Rate character type

* docs: fix lint error

* feat: update Rate character type

* feat: update Rate character type
2022-05-19 09:46:26 +08:00

1.7 KiB

order title
5
zh-CN en-US
异步加载 Asynchronous loading

zh-CN

异步加载树节点。

en-US

Asynchronous loading tree node.

import React, { useState } from 'react';
import { TreeSelect } from 'antd';
import type { DefaultOptionType } from 'antd/es/select';
import type { TreeSelectProps } from 'antd';

const App: React.FC = () => {
  const [value, setValue] = useState<string>();
  const [treeData, setTreeData] = useState<Omit<DefaultOptionType, 'label'>[]>([
    { id: 1, pId: 0, value: '1', title: 'Expand to load' },
    { id: 2, pId: 0, value: '2', title: 'Expand to load' },
    { id: 3, pId: 0, value: '3', title: 'Tree Node', isLeaf: true },
  ]);

  const genTreeNode = (parentId: number, isLeaf = false) => {
    const random = Math.random().toString(36).substring(2, 6);
    return {
      id: random,
      pId: parentId,
      value: random,
      title: isLeaf ? 'Tree Node' : 'Expand to load',
      isLeaf,
    };
  };

  const onLoadData: TreeSelectProps['loadData'] = ({ id }) =>
    new Promise(resolve => {
      setTimeout(() => {
        setTreeData(
          treeData.concat([genTreeNode(id, false), genTreeNode(id, true), genTreeNode(id, true)]),
        );
        resolve(undefined);
      }, 300);
    });

  const onChange = (newValue: string) => {
    console.log(newValue);
    setValue(newValue);
  };

  return (
    <TreeSelect
      treeDataSimpleMode
      style={{ width: '100%' }}
      value={value}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      placeholder="Please select"
      onChange={onChange}
      loadData={onLoadData}
      treeData={treeData}
    />
  );
};

export default App;