树选择 TreeSelect - Ant Design


本站和网页 https://ant.design/components/tree-select-cn/ 的作者无关,不对其内容负责。快照谨为网络故障时之索引,不代表被搜索网站的即时页面。

树选择 TreeSelect - Ant Design
Enable JavaScript to run this app.
Ant Design⌘ K设计研发组件博客资源5.1.0更多中En组件总览通用Button按钮Icon图标Typography排版布局Divider分割线Grid栅格Layout布局Space间距导航Anchor锚点Breadcrumb面包屑Dropdown下拉菜单Menu导航菜单Pagination分页Steps步骤条数据录入AutoComplete自动完成Cascader级联选择Checkbox多选框DatePicker日期选择框Form表单Input输入框InputNumber数字输入框Mentions提及Radio单选框Rate评分Select选择器Slider滑动输入条Switch开关TimePicker时间选择框Transfer穿梭框TreeSelect树选择Upload上传数据展示Avatar头像Badge徽标数Calendar日历Card卡片Carousel走马灯Collapse折叠面板Descriptions描述列表Empty空状态Image图片List列表Popover气泡卡片QRCode二维码Segmented分段控制器Statistic统计数值Table表格Tabs标签页Tag标签Timeline时间轴Tooltip文字提示Tour漫游式引导Tree树形控件反馈Alert警告提示Drawer抽屉Message全局提示Modal对话框Notification通知提醒框Popconfirm气泡确认框Progress进度条Result结果Skeleton骨架屏Spin加载中其他Affix固钉App包裹组件ConfigProvider全局化配置FloatButton悬浮按钮Watermark水印何时使用代码演示基本多选从数据直接生成可勾选异步加载线性样式弹出位置自定义状态APITree propsTree 方法TreeNode propsFAQonChange 时如何获得父节点信息?自定义 Option 样式导致滚动异常怎么办?TreeSelect树选择Transfer穿梭框Upload上传相关资源Ant Design ChartsAnt Design ProAnt Design Pro ComponentsAnt Design MobileAnt Design Landing-首页模板集Scaffolds-脚手架市场Umi-React 应用开发框架dumi-组件/文档研发工具qiankun-微前端框架ahooks-React Hooks 库Ant Motion-设计动效国内镜像站点 🇨🇳社区Awesome Ant DesignMediumTwitterAnt Design 语雀专栏Ant Design 知乎专栏体验科技专栏SEE Conf-蚂蚁体验科技大会加入我们帮助GitHub更新日志常见问题报告 Bug讨论列表讨论区StackOverflowSegmentFault更多产品语雀-构建你的数字花园AntV-数据可视化解决方案Egg-企业级 Node.js 框架Kitchen-Sketch 工具集蚂蚁体验科技主题编辑器Made with ❤ by蚂蚁集团和 Ant Design 开源社区树型选择控件。何时使用类似 Select 的选择控件,可选择的数据结构是一个树形结构时,可以使用 TreeSelect,例如公司层级、学科系统、分类目录等等。代码演示Please select基本最简单的用法。TypeScriptJavaScriptimport React, { useState } from 'react';
import { TreeSelect } from 'antd';
const treeData = [
value: 'parent 1',
title: 'parent 1',
children: [
value: 'parent 1-0',
title: 'parent 1-0',
children: [
value: 'leaf1',
title: 'leaf1',
},
value: 'leaf2',
title: 'leaf2',
},
],
},
value: 'parent 1-1',
title: 'parent 1-1',
children: [
value: 'leaf3',
title: <b style={{ color: '#08c' }}>leaf3</b>,
},
],
},
],
},
];
const App: React.FC = () => {
const [value, setValue] = useState<string | undefined>(undefined);
const onChange = (newValue: string) => {
setValue(newValue);
};
return (
<TreeSelect
showSearch
style={{ width: '100%' }}
value={value}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="Please select"
allowClear
treeDefaultExpandAll
onChange={onChange}
treeData={treeData}
/>
);
};
export default App;
Please select从数据直接生成使用 treeData 把 JSON 数据直接生成树结构。TypeScriptJavaScriptimport React, { useState } from 'react';
import { TreeSelect } from 'antd';
const treeData = [
title: 'Node1',
value: '0-0',
children: [
title: 'Child Node1',
value: '0-0-1',
},
title: 'Child Node2',
value: '0-0-2',
},
],
},
title: 'Node2',
value: '0-1',
},
];
const App: React.FC = () => {
const [value, setValue] = useState<string>();
const onChange = (newValue: string) => {
console.log(newValue);
setValue(newValue);
};
return (
<TreeSelect
style={{ width: '100%' }}
value={value}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
treeData={treeData}
placeholder="Please select"
treeDefaultExpandAll
onChange={onChange}
/>
);
};
export default App;
Please select异步加载异步加载树节点。TypeScriptJavaScriptimport React, { useState } from 'react';
import type { TreeSelectProps } from 'antd';
import { TreeSelect } from 'antd';
import type { DefaultOptionType } from 'antd/es/select';
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;
topLefttopRightbottomLeftbottomRightPlease select弹出位置可以通过 placement 手动指定弹出的位置。TypeScriptJavaScriptimport React, { useState } from 'react';
import type { RadioChangeEvent } from 'antd';
import { Radio, TreeSelect } from 'antd';
import type { SelectCommonPlacement } from 'antd/es/_util/motion';
const treeData = [
value: 'parent 1',
title: 'parent 1',
children: [
value: 'parent 1-0',
title: 'parent 1-0',
children: [
value: 'leaf1',
title: 'leaf1',
},
value: 'leaf2',
title: 'leaf2',
},
],
},
value: 'parent 1-1',
title: 'parent 1-1',
children: [
value: 'leaf3',
title: <b style={{ color: '#08c' }}>leaf3</b>,
},
],
},
],
},
];
const App: React.FC = () => {
const [placement, SetPlacement] = useState<SelectCommonPlacement>('topLeft');
const placementChange = (e: RadioChangeEvent) => {
SetPlacement(e.target.value);
};
return (
<>
<Radio.Group value={placement} onChange={placementChange}>
<Radio.Button value="topLeft">topLeft</Radio.Button>
<Radio.Button value="topRight">topRight</Radio.Button>
<Radio.Button value="bottomLeft">bottomLeft</Radio.Button>
<Radio.Button value="bottomRight">bottomRight</Radio.Button>
</Radio.Group>
<br />
<br />
<TreeSelect
showSearch
dropdownStyle={{ maxHeight: 400, overflow: 'auto', minWidth: 300 }}
placeholder="Please select"
dropdownMatchSelectWidth={false}
placement={placement}
allowClear
treeDefaultExpandAll
treeData={treeData}
/>
</>
);
};
export default App;
 Please select多选多选的树选择。TypeScriptJavaScriptimport React, { useState } from 'react';
import { TreeSelect } from 'antd';
const treeData = [
value: 'parent 1',
title: 'parent 1',
children: [
value: 'parent 1-0',
title: 'parent 1-0',
children: [
value: 'leaf1',
title: 'my leaf',
},
value: 'leaf2',
title: 'your leaf',
},
],
},
value: 'parent 1-1',
title: 'parent 1-1',
children: [
value: 'sss',
title: <b style={{ color: '#08c' }}>sss</b>,
},
],
},
],
},
];
const App: React.FC = () => {
const [value, setValue] = useState<string>();
const onChange = (newValue: string) => {
console.log(newValue);
setValue(newValue);
};
return (
<TreeSelect
showSearch
style={{ width: '100%' }}
value={value}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="Please select"
allowClear
multiple
treeDefaultExpandAll
onChange={onChange}
treeData={treeData}
/>
);
};
export default App;
Node1 可勾选使用勾选框实现多选功能。TypeScriptJavaScriptimport React, { useState } from 'react';
import { TreeSelect } from 'antd';
const { SHOW_PARENT } = TreeSelect;
const treeData = [
title: 'Node1',
value: '0-0',
key: '0-0',
children: [
title: 'Child Node1',
value: '0-0-0',
key: '0-0-0',
},
],
},
title: 'Node2',
value: '0-1',
key: '0-1',
children: [
title: 'Child Node3',
value: '0-1-0',
key: '0-1-0',
},
title: 'Child Node4',
value: '0-1-1',
key: '0-1-1',
},
title: 'Child Node5',
value: '0-1-2',
key: '0-1-2',
},
],
},
];
const App: React.FC = () => {
const [value, setValue] = useState(['0-0-0']);
const onChange = (newValue: string[]) => {
console.log('onChange ', value);
setValue(newValue);
};
const tProps = {
treeData,
value,
onChange,
treeCheckable: true,
showCheckedStrategy: SHOW_PARENT,
placeholder: 'Please select',
style: {
width: '100%',
},
};
return <TreeSelect {...tProps} />;
};
export default App;
treeLinetreeLineshowLeafIconshowLeafIcon线性样式通过 treeLine 配置线性样式。TypeScriptJavaScriptimport React, { useState } from 'react';
import { Space, Switch, TreeSelect } from 'antd';
const treeData = [
value: 'parent 1',
title: 'parent 1',
children: [
value: 'parent 1-0',
title: 'parent 1-0',
children: [
value: 'leaf1',
title: 'leaf1',
},
value: 'leaf2',
title: 'leaf2',
},
],
},
value: 'parent 1-1',
title: 'parent 1-1',
children: [
value: 'sss',
title: 'sss',
},
],
},
],
},
];
const App: React.FC = () => {
const [treeLine, setTreeLine] = useState(true);
const [showLeafIcon, setShowLeafIcon] = useState(false);
return (
<Space direction="vertical">
<Switch
checkedChildren="treeLine"
unCheckedChildren="treeLine"
checked={treeLine}
onChange={() => setTreeLine(!treeLine)}
/>
<Switch
disabled={!treeLine}
checkedChildren="showLeafIcon"
unCheckedChildren="showLeafIcon"
checked={showLeafIcon}
onChange={() => setShowLeafIcon(!showLeafIcon)}
/>
<TreeSelect
treeLine={treeLine && { showLeafIcon }}
style={{ width: 300 }}
treeData={treeData}
/>
</Space>
);
};
export default App;
Error Warning multiple自定义状态使用 status 为 TreeSelect 添加状态,可选 error 或者 warning。TypeScriptJavaScriptimport React from 'react';
import { Space, TreeSelect } from 'antd';
const App: React.FC = () => (
<Space direction="vertical" style={{ width: '100%' }}>
<TreeSelect status="error" style={{ width: '100%' }} placeholder="Error" />
<TreeSelect
status="warning"
style={{ width: '100%' }}
multiple
placeholder="Warning multiple"
/>
</Space>
);
export default App;
APITree props参数说明类型默认值版本allowClear显示清除按钮booleanfalseautoClearSearchValue当多选模式下值被选择,自动清空搜索框booleantruebordered是否显示边框booleantruedefaultValue指定默认选中的条目string | string[]-disabled是否禁用booleanfalsepopupClassName下拉菜单的 className 属性string-4.23.0dropdownMatchSelectWidth下拉菜单和选择器同宽。默认将设置 min-width,当值小于选择框宽度时会被忽略。false 时会关闭虚拟滚动boolean | numbertruedropdownRender自定义下拉框内容(originNode: ReactNode, props) => ReactNode-dropdownStyle下拉菜单的样式object-fieldNames自定义节点 label、value、children 的字段object{ label: label, value: value, children: children }4.17.0filterTreeNode是否根据输入项进行筛选,默认用 treeNodeFilterProp 的值作为要筛选的 TreeNode 的属性值boolean | function(inputValue: string, treeNode: TreeNode) (函数需要返回 bool 值)functiongetPopupContainer菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。示例function(triggerNode)() => document.bodylabelInValue是否把每个选项的 label 包装到 value 中,会把 value 类型从 string 变为 {value: string, label: ReactNode, halfChecked(treeCheckStrictly 时有效): string[] } 的格式booleanfalselistHeight设置弹窗滚动高度number256loadData异步加载数据function(node)-maxTagCount最多显示多少个 tag,响应式模式会对性能产生损耗number | responsive-responsive: 4.10maxTagPlaceholder隐藏 tag 时显示的内容ReactNode | function(omittedValues)-multiple支持多选(当设置 treeCheckable 时自动变为 true)booleanfalsenotFoundContent当下拉列表为空时显示的内容ReactNodeNot Foundplaceholder选择框默认文字string-placement选择框弹出的位置bottomLeft bottomRight topLeft topRightbottomLeftsearchValue搜索框的值,可以通过 onSearch 获取用户输入string-showArrow是否显示 suffixIcon,单选模式下默认 trueboolean-showCheckedStrategy配置 treeCheckable 时,定义选中项回填的方式。TreeSelect.SHOW_ALL: 显示所有选中节点(包括父节点)。TreeSelect.SHOW_PARENT: 只显示父节点(当父节点下所有子节点都选中时)。 默认只显示子节点TreeSelect.SHOW_ALL | TreeSelect.SHOW_PARENT | TreeSelect.SHOW_CHILDTreeSelect.SHOW_CHILDshowSearch是否支持搜索框boolean单选:false | 多选:truesize选择框大小large | middle | small-status设置校验状态'error' | 'warning'-4.19.0suffixIcon自定义的选择框后缀图标, 多选模式下必须同时设置 showArrow 为 trueReactNode-switcherIcon自定义树节点的展开/折叠图标ReactNode | ((props: AntTreeNodeProps) => ReactNode)-renderProps: 4.20.0tagRender自定义 tag 内容,多选时生效(props) => ReactNode-treeCheckable显示 CheckboxbooleanfalsetreeCheckStrictlycheckable 状态下节点选择完全受控(父子节点选中状态不再关联),会使得 labelInValue 强制为 truebooleanfalsetreeDatatreeNodes 数据,如果设置则不需要手动构造 TreeNode 节点(value 在整个树范围内唯一)array<{value, title, children, [disabled, disableCheckbox, selectable, checkable]}>[]treeDataSimpleMode使用简单格式的 treeData,具体设置参考可设置的类型 (此时 treeData 应变为这样的数据结构: [{id:1, pId:0, value:'1', title:"test1",...},...], pId 是父节点的 id)boolean | object<{ id: string, pId: string, rootPId: string }>falsetreeDefaultExpandAll默认展开所有树节点booleanfalsetreeDefaultExpandedKeys默认展开的树节点string[]-treeExpandAction点击节点 title 时的展开逻辑,可选:false | click | doubleClickstring | booleanfalse4.21.0treeExpandedKeys设置展开的树节点string[]-treeIcon是否展示 TreeNode title 前的图标,没有默认样式,如设置为 true,需要自行定义图标相关样式booleanfalsetreeLine是否展示线条样式,请参考 Tree - showLineboolean | objectfalse4.17.0treeLoadedKeys(受控)已经加载的节点,需要配合 loadData 使用string[][]treeNodeFilterProp输入项过滤对应的 treeNode 属性stringvaluetreeNodeLabelProp作为显示的 prop 设置stringtitlevalue指定当前选中的条目string | string[]-virtual设置 false 时关闭虚拟滚动booleantrue4.1.0onChange选中树节点时调用此函数function(value, label, extra)-onDropdownVisibleChange展开下拉菜单的回调function(open)-onSearch文本框值变化时的回调function(value: string)-onSelect被选中时调用function(value, node, extra)-onTreeExpand展示节点时调用function(expandedKeys)-Tree 方法名称描述版本blur()移除焦点focus()获取焦点TreeNode props建议使用 treeData 来代替 TreeNode,免去手工构造麻烦参数说明类型默认值版本checkable当树为 Checkbox 时,设置独立节点是否展示 Checkboxboolean-disableCheckbox禁掉 Checkboxbooleanfalsedisabled是否禁用booleanfalseisLeaf是否是叶子节点booleanfalsekey此项必须设置(其值在整个树范围内唯一)string-selectable是否可选booleantruetitle树节点显示的内容ReactNode---value默认根据此属性值进行筛选(其值在整个树范围内唯一)string-FAQonChange 时如何获得父节点信息?从性能角度考虑,我们默认不透出父节点信息。你可以这样获得:https://codesandbox.io/s/wk080nn81k自定义 Option 样式导致滚动异常怎么办?请参考 Select 的 FAQ。