# 树选择

- 页面: https://jiguang132.com/zh/resources/ant-design/docs/tree-select
- 资源: Ant Design (https://jiguang132.com/zh/resources/ant-design.md)
- 全部指南: https://jiguang132.com/zh/resources/ant-design/docs.md

树型选择控件。


## 何时使用 {#when-to-use}

类似 Select 的选择控件，可选择的数据结构是一个树形结构时，可以使用 TreeSelect，例如公司层级、学科系统、分类目录等等。

## 代码演示 {#examples}


- 基本 · `basic`
- 多选 · `multiple`
- 从数据直接生成 · `treeData`
- 可勾选 · `checkable`
- 异步加载 · `async`
- 线性样式 · `treeLine`
- 弹出位置 · `placement`
- 形态变体 · `variant`
- 自定义状态 · `status`
- 最大选中数量 · `maxCount`
- 前后缀 · `suffix`
- 自定义语义结构的样式和类 · `style-class`



## API

通用属性参考：[通用属性](#jguang-common-props)

### Tree props

| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider#component-config) |
| --- | --- | --- | --- | --- | --- |
| allowClear | 自定义清除按钮 | boolean \| { clearIcon?: ReactNode } | false | 5.8.0: 支持对象形式 | × |
| ~~autoClearSearchValue~~ | 当多选模式下值被选择，自动清空搜索框 | boolean | true |  | × |
| ~~bordered~~ | 是否带边框，请使用 `variant` 替代 | boolean | true | - | × |
| classNames | 用于自定义组件内部各语义化结构的 class，支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - |  | 5.25.0 |
| defaultOpen | 是否默认展开下拉菜单 | boolean | - |  | × |
| defaultValue | 指定默认选中的条目 | string \| string\[] | - |  | × |
| disabled | 是否禁用 | boolean | false |  | × |
| ~~dropdownClassName~~ | 下拉菜单的 className 属性，请使用 `classNames.popup.root` 替代 | string | - | - | × |
| ~~dropdownMatchSelectWidth~~ | 下拉菜单和选择器是否同宽，请使用 `popupMatchSelectWidth` 替代 | boolean \| number | true | - | × |
| ~~popupClassName~~ | 下拉菜单的 className 属性，使用 `classNames.popup.root` 替换 | string | - | 4.23.0 | × |
| popupMatchSelectWidth | 下拉菜单和选择器同宽。默认将设置 `min-width`，当值小于选择框宽度时会被忽略。false 时会关闭虚拟滚动 | boolean \| number | true | 5.5.0 | × |
| ~~dropdownRender~~ | 自定义下拉框内容，使用 `popupRender` 替换 | (originNode: ReactElement) => ReactNode | - |  | × |
| popupRender | 自定义下拉框内容 | (originNode: ReactElement) => ReactNode | - |  | × |
| ~~dropdownStyle~~ | 下拉菜单的样式，使用 `styles.popup.root` 替换 | object | - |  | × |
| fieldNames | 自定义节点 label、value、children 的字段 | object | { label: `label`, value: `value`, children: `children` } | 4.17.0 | × |
| ~~filterTreeNode~~ | 是否根据输入项进行筛选，默认用 treeNodeFilterProp 的值作为要筛选的 TreeNode 的属性值 | boolean \| function(inputValue: string, treeNode: TreeNode) (函数需要返回 bool 值) | function |  | × |
| getPopupContainer | 菜单渲染父节点。默认渲染到 body 上，如果你遇到菜单滚动定位问题，试试修改为滚动的区域，并相对其定位。[示例](https://codepen.io/afc163/pen/zEjNOy?editors=0010) | function(triggerNode) | () => document.body |  | × |
| labelInValue | 是否把每个选项的 label 包装到 value 中，会把 value 类型从 `string` 变为 {value: string, label: ReactNode, halfChecked: boolean(选项列表是否为半选状态，并且不会展示到值中) } 的格式 | boolean | false |  | × |
| listHeight | 设置弹窗滚动高度 | number | 256 |  | × |
| loadData | 异步加载数据。在过滤时不会调用以防止网络堵塞，可参考 FAQ 获得更多内容 | function(node) | - |  | × |
| maxCount | 指定可选中的最多 items 数量，仅在 `multiple=true` 时生效。如果此时 (`showCheckedStrategy = 'SHOW_ALL'` 且未开启 `treeCheckStrictly`)，或使用 `showCheckedStrategy = 'SHOW_PARENT'`，则maxCount无效。 | number | - | 5.23.0 | × |
| maxTagCount | 最多显示多少个 tag，响应式模式会对性能产生损耗 | number \| `responsive` | - | responsive: 4.10 | × |
| maxTagPlaceholder | 隐藏 tag 时显示的内容 | ReactNode \| function(omittedValues) | - |  | × |
| maxTagTextLength | 最大显示的 tag 文本长度 | number | - |  | × |
| multiple | 支持多选（当设置 treeCheckable 时自动变为 true） | boolean | false |  | × |
| notFoundContent | 当下拉列表为空时显示的内容 | ReactNode | `暂无数据` |  | × |
| open | 是否展开下拉菜单 | boolean | - |  | × |
| placeholder | 选择框默认文字 | string | - |  | × |
| placement | 选择框弹出的位置 | `bottomLeft` `bottomRight` `topLeft` `topRight` | bottomLeft |  | × |
| prefix | 自定义前缀 | ReactNode | - | 5.22.0 | × |
| ~~searchValue~~ | 搜索框的值，可以通过 `onSearch` 获取用户输入 | string | - |  | × |
| ~~showArrow~~ | 是否显示箭头图标，请使用 `suffixIcon={null}` 替代 | boolean | true | - | × |
| showCheckedStrategy | 配置 `treeCheckable` 时，定义选中项回填的方式。`TreeSelect.SHOW_ALL`: 显示所有选中节点(包括父节点)。`TreeSelect.SHOW_PARENT`: 只显示父节点(当父节点下所有子节点都选中时)。 默认只显示子节点 | `TreeSelect.SHOW_ALL` \| `TreeSelect.SHOW_PARENT` \| `TreeSelect.SHOW_CHILD` | `TreeSelect.SHOW_CHILD` |  | × |
| showSearch | 是否支持搜索框 | boolean \| [Object](#showsearch) | 单选：false \| 多选：true |  | × |
| size | 选择框大小 | `large` \| `medium` \| `small` | - |  | × |
| status | 设置校验状态 | 'error' \| 'warning' | - | 4.19.0 | × |
| styles | 用于自定义组件内部各语义化结构的行内 style，支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - |  | 5.25.0 |
| suffixIcon | 自定义的选择框后缀图标 | ReactNode | `<DownOutlined />` |  | × |
| switcherIcon | 自定义树节点的展开/折叠图标 | ReactNode \| ((props: AntTreeNodeProps) => ReactNode) | - | renderProps: 4.20.0 | 5.28.0 |
| tagRender | 自定义 tag 内容，多选时生效 | (props) => ReactNode | - |  | × |
| treeCheckable | 显示 Checkbox | boolean | false |  | × |
| treeCheckStrictly | `checkable` 状态下节点选择完全受控（父子节点选中状态不再关联），会使得 `labelInValue` 强制为 true | boolean | false |  | × |
| treeData | treeNodes 数据，如果设置则不需要手动构造 TreeNode 节点（value 在整个树范围内唯一） | array&lt;{value, title, children, \[disabled, disableCheckbox, selectable, checkable]}> | \[] |  | × |
| treeDataSimpleMode | 使用简单格式的 treeData，具体设置参考可设置的类型 (此时 treeData 应变为这样的数据结构: \[{id:1, pId:0, value:'1', title:"test1",...},...]， `pId` 是父节点的 id) | boolean \| object&lt;{ id: string, pId: string, rootPId: string }> | false |  | × |
| treeDefaultExpandAll | 默认展开所有树节点 | boolean | false |  | × |
| treeDefaultExpandedKeys | 默认展开的树节点 | string\[] | - |  | × |
| treeExpandAction | 点击节点 title 时的展开逻辑，可选：false \| `click` \| `doubleClick` | string \| boolean | false | 4.21.0 | × |
| treeExpandedKeys | 设置展开的树节点 | string\[] | - |  | × |
| treeIcon | 是否展示 TreeNode title 前的图标，没有默认样式，如设置为 true，需要自行定义图标相关样式 | boolean | false |  | × |
| treeLine | 是否展示线条样式，请参考 [Tree - showLine](/components/tree#tree-demo-line) | boolean \| object | false | 4.17.0 | × |
| treeLoadedKeys | （受控）已经加载的节点，需要配合 `loadData` 使用 | string[] | [] |  | × |
| ~~treeNodeFilterProp~~ | 输入项过滤对应的 treeNode 属性 | string | `value` |  | × |
| treeNodeLabelProp | 作为显示的 prop 设置 | string | `title` |  | × |
| treeTitleRender | 自定义渲染节点 | (nodeData) => ReactNode | - | 5.12.0 | × |
| value | 指定当前选中的条目 | string \| string\[] | - |  | × |
| variant | 形态变体 | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 | 5.19.0 |
| virtual | 设置 false 时关闭虚拟滚动 | boolean | true | 4.1.0 | × |
| onChange | 选中树节点时调用此函数 | function(value, label, extra) | - |  | × |
| onClear | 清除内容时回调 | () => void | - | - | × |
| ~~onDropdownVisibleChange~~ | 展开下拉菜单的回调，使用 `onOpenChange` 替换 | (open: boolean) => void | - |  | × |
| onOpenChange | 展开下拉菜单的回调 | (open: boolean) => void | - |  | × |
| onPopupScroll | 下拉列表滚动时的回调 | (event: UIEvent) => void | - | 5.17.0 | × |
| ~~onSearch~~ | 文本框值变化时的回调 | function(value: string) | - |  | × |
| onSelect | 被选中时调用 | function(value, node, extra) | - |  | × |
| onTreeExpand | 展示节点时调用 | function(expandedKeys) | - |  | × |

### showSearch

| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| autoClearSearchValue | 当多选模式下值被选择，自动清空搜索框 | boolean | true |  |
| filterTreeNode | 是否根据输入项进行筛选，默认用 treeNodeFilterProp 的值作为要筛选的 TreeNode 的属性值 | boolean \| function(inputValue: string, treeNode: TreeNode) (函数需要返回 bool 值) | function |  |
| searchValue | 搜索框的值，可以通过 `onSearch` 获取用户输入 | string | - |  |
| treeNodeFilterProp | 输入项过滤对应的 treeNode 属性 | string | `value` |  |
| onSearch | 文本框值变化时的回调 | function(value: string) | - |  |

### Tree 方法 {#tree-methods}

| 名称    | 描述     | 版本 |
| ------- | -------- | ---- |
| blur()  | 移除焦点 |      |
| focus() | 获取焦点 |      |

### TreeNode props

> 建议使用 treeData 来代替 TreeNode，免去手动构造的麻烦

| 参数            | 说明                                               | 类型      | 默认值 | 版本 |
| --------------- | -------------------------------------------------- | --------- | ------ | ---- |
| checkable       | 当树为 Checkbox 时，设置独立节点是否展示 Checkbox  | boolean   | -      |      |
| disableCheckbox | 禁掉 Checkbox                                      | boolean   | false  |      |
| disabled        | 是否禁用                                           | boolean   | false  |      |
| isLeaf          | 是否是叶子节点                                     | boolean   | false  |      |
| key             | 此项必须设置（其值在整个树范围内唯一）             | string    | -      |      |
| selectable      | 是否可选                                           | boolean   | true   |      |
| title           | 树节点显示的内容                                   | ReactNode | `---`  |      |
| value           | 默认根据此属性值进行筛选（其值在整个树范围内唯一） | string    | -      |      |

## Semantic DOM

| 语义节点 | 原生说明 | 版本 |
| --- | --- | --- |
| `root` | 根元素，设置树选择器的基础样式、边框、圆角容器样式 | — |
| `prefix` | 前缀元素，设置前缀内容的布局和样式 | — |
| `placeholder` | 占位符元素，包含占位符文本的字体样式和颜色 | — |
| `input` | 输入框元素，设置文本输入、搜索、选择值显示等输入框的核心交互样式 | — |
| `suffix` | 后缀元素，设置后缀内容、清除按钮、下拉箭头等后缀区域的样式 | — |
| `popup.root` | 弹出菜单元素，设置下拉树形选择面板的定位、层级、背景、边框、阴影等弹层样式 | — |
| `popup.item` | 弹出菜单条目元素，设置树节点选项的样式、悬停态、选中态等交互状态 | — |
| `popup.itemTitle` | 弹出菜单标题元素，设置树节点标题文字的显示样式 | — |
| `popup.itemSwitcher` | 弹出菜单切换器元素，设置树节点展开/收起按钮的样式和背景 | 6.4.0 |
| `content` | 多选容器，包含已选项的布局、间距、换行相关样式 (多选模式) | — |
| `item` | 多选项元素，包含边框、背景、内边距、外边距样式 (多选模式) | — |
| `itemContent` | 多选项内容区域，包含文字的省略样式 (多选模式) | — |
| `itemRemove` | 多选项移除按钮，包含字体相关样式 (多选模式) | — |

语义说明来源: `vendor/.dumi/theme/common/TreeSelectSemanticTemplate.tsx`

## 主题变量（Design Token）{#design-token}

类型、继承关系和原生令牌声明保持固定源码原文；默认值由原生主题计算，并可能受 ConfigProvider 覆盖。本表不伪造静态默认值。

原生 ComponentToken 未声明可直接提取的自有字段；共享令牌或继承关系以以下声明为准。

声明来源: `vendor/components/tree-select/style/index.ts`

```ts
import { unit } from '@ant-design/cssinjs';

import { getStyle as getCheckboxStyle } from '../../checkbox/style';

import type {
  AliasToken,
  CSSUtil,
  FullToken,
  GenerateStyle,
  GetDefaultToken,
} from '../../theme/internal';

import { genStyleHooks, mergeToken } from '../../theme/internal';

import type { TreeSharedToken } from '../../tree/style';

import { genTreeStyle, initComponentToken } from '../../tree/style';

export interface ComponentToken extends TreeSharedToken {}

interface TreeSelectToken extends FullToken<'TreeSelect'> {
  treePrefixCls: string;
}
```

## FAQ

### onChange 时如何获得父节点信息？ {#faq-parent-node-info}

从性能角度考虑，我们默认不透出父节点信息。你可以这样获得：<https://codesandbox.io/s/get-parent-node-in-onchange-eb1608>

### 自定义 Option 样式导致滚动异常怎么办？ {#faq-custom-option-scroll}

请参考 Select 的 [FAQ](/components/select)。

### 为何在搜索时 `loadData` 不会触发展开？ {#faq-load-data-expand}

在 v4 alpha 版本中，默认在搜索时亦会进行搜索。但是经反馈，在输入时会快速阻塞网络。因而改为搜索不触发 `loadData`。但是你仍然可以通过 `filterTreeNode` 处理异步加载逻辑：

```tsx
<TreeSelect
  filterTreeNode={(input, treeNode) => {
    const match = YOUR_LOGIC_HERE;

    if (match && !treeNode.isLeaf && !treeNode.children) {
      // Do some loading logic
    }

    return match;
  }}
/>
```

### 为何弹出框不能横向滚动？ {#faq-popup-not-scroll}

关闭虚拟滚动即可，因为开启虚拟滚动时无法准确的测量完整列表的 `scrollWidth`。


## 原生通用属性 {#jguang-common-props}


> Tips: 以下通用属性适用于 antd 大部分组件，不支持的组件会单独说明。

| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| style | 自定义样式 | CSSProperties | - |
| className | 自定义类名 | string | - |
| rootClassName | 添加在组件最外层的 className | string | - |
| autoFocus | 自动获取焦点，仅对表单类、链接、交互容器等可聚焦元素生效 | boolean | false |


## 安装并复现示例

```bash
npm install antd@6.6.5 @ant-design/icons@6.3.4 dayjs@1.11.23
```

使用 ConfigProvider 和原生 App，并单独配置 dayjs 语言。每个示例在查看代码中列出完整源码文件和额外固定依赖。示例名称用于选择演示，不是组件通用属性。主题、语言与 SSR 初始化见资源安装指南。

## 原生类型参考

源码查看器包含未修改的原生实现和以下声明文件，继承类型仍位于原生包中。代码中的英文注释保留为源码参考。

- `vendor/components/tree-select/index.tsx`
- `vendor/components/tree-select/style/index.ts`

## 来源与许可

https://github.com/ant-design/ant-design/tree/4a39f54842eade4e565ab336ef6097cd7e723cdd

保留原生中英文正文与可执行示例；官网专用的嵌入章节和令牌表格在本地展开。Ant Design 使用 MIT 许可，另列依赖的许可证也需保留。上传预览禁止向外发起请求，不提供后端服务。

---

JGuang 全部资源索引: https://jiguang132.com/llms.txt
