JGuang

选择器

Select · Ant Design

交互预览
npm install antd@6.6.5 @ant-design/icons@6.3.4 dayjs@1.11.23

选择器

下拉选择器。

何时使用

  • 弹出一个下拉菜单给用户选择操作,用于代替原生的选择器,或者需要一个更优雅的多选器时。
  • 当选项少时(少于 5 项),建议直接将选项平铺,使用 Radio 是更好的选择。
  • 如果你在寻找一个可输可选的输入框,那你可能需要 AutoComplete。

代码演示

  • 基本使用 · basic

  • 带搜索框 · search

  • 自定义搜索 · search-filter-option

  • 多字段搜索 · search-multi-field

  • 多选 · multiple

  • 三种大小 · size

  • 自定义下拉选项 · option-render

  • 带排序的搜索 · search-sort

  • 标签 · tags

  • 分组 · optgroup

  • 联动 · coordinate

  • 获得选项的文本 · label-in-value

  • 自动分词 · automatic-tokenization

  • 自定义分词 · custom-tokenization

  • 搜索用户 · select-users

  • 前后缀 · suffix

  • 扩展菜单 · custom-dropdown-menu

  • 隐藏已选择选项 · hide-selected

  • 形态变体 · variant

  • 自定义选择标签 · custom-tag-render

  • 自定义选中 label · custom-label-render

  • 响应式 maxTagCount · responsive

  • 大数据 · big-data

  • 自定义状态 · status

  • 弹出位置 · placement

  • 最大选中数量 · maxCount

  • 自定义语义结构的样式和类 · style-class

API

通用属性参考:通用属性

Select props

参数说明类型默认值版本全局配置
allowClear自定义清除按钮boolean | { clearIcon?: ReactNode }false5.8.0: 支持对象类型6.4.0
autoClearSearchValue是否在选中项后清空搜索框,只在 mode 为 multiple 或 tags 时有效booleantrue×
bordered是否带边框,请使用 variant 替代booleantrue-×
classNames用于自定义 Select 组件内部各语义化结构的 class,支持对象或函数Record<SemanticDOM, string> | (info: { props }) => Record<SemanticDOM, string>-5.25.0
defaultActiveFirstOption是否默认高亮第一个选项booleantrue×
defaultOpen是否默认展开下拉菜单boolean-×
defaultValue指定默认选中的条目string | string[] |<br />number | number[] | <br />LabeledValue | LabeledValue[]-×
disabled是否禁用booleanfalse×
dropdownClassName下拉菜单的 className 属性,请使用 classNames.popup.root 替代string--×
dropdownMatchSelectWidth下拉菜单和选择器是否同宽,请使用 popupMatchSelectWidth 替代boolean | numbertrue-×
popupClassName下拉菜单的 className 属性,使用 classNames.popup.root 替换string-4.23.0×
popupMatchSelectWidth下拉菜单和选择器同宽。默认将设置 min-width,当值小于选择框宽度时会被忽略。false 时会关闭虚拟滚动boolean | numbertrue5.5.0×
dropdownRender自定义下拉框内容,使用 popupRender 替换(originNode: ReactElement) => ReactNode-×
popupRender自定义下拉框内容(originNode: ReactElement) => ReactNode-5.25.0×
dropdownStyle下拉菜单的 style 属性,使用 styles.popup.root 替换CSSProperties-×
fieldNames自定义节点 label、value、options、groupLabel 的字段object{ label: label, value: value, options: options, groupLabel: label }4.17.0(groupLabel 在 5.6.0 新增)×
filterOption是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true,反之则返回 false。示例boolean | function(inputValue, option)true×
filterSort搜索时对筛选结果项的排序函数, 类似Array.sort里的 compareFunction(optionA: Option, optionB: Option, info: { searchValue: string }) => number-searchValue: 5.19.0×
getPopupContainer菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。示例function(triggerNode)() => document.body×
labelInValue是否把每个选项的 label 包装到 value 中,会把 Select 的 value 类型从 string 变为 { value: string, label: ReactNode } 的格式booleanfalse×
listHeight设置弹窗滚动高度number256×
loading加载中状态booleanfalse×
loadingIcon自定义的加载图标ReactNode<LoadingOutlined spin />6.4.06.4.0
maxCount指定可选中的最多 items 数量,仅在 mode 为 multiple 或 tags 时生效number-5.13.0×
maxTagCount最多显示多少个 tag,响应式模式会对性能产生损耗number | responsive-responsive: 4.10×
maxTagPlaceholder隐藏 tag 时显示的内容ReactNode | function(omittedValues)-×
maxTagTextLength最大显示的 tag 文本长度number-×
menuItemSelectedIcon自定义多选时当前选中的条目图标ReactNode<CheckOutlined />6.4.0
mode设置 Select 的模式为多选或标签multiple | tags-×
notFoundContent当下拉列表为空时显示的内容ReactNode暂无数据×
open是否展开下拉菜单boolean-×
optionFilterProp已废弃,见 showSearch.optionFilterProp×
optionLabelProp回填到选择框的 Option 的属性值,默认是 Option 的子元素。比如在子元素需要高亮效果时,此值可以设为 value。示例stringchildren×
options数据化配置选项内容,相比 jsx 定义会获得更好的渲染性能{ label, value }[]-×
optionRender自定义渲染下拉选项(option: FlattenOptionData<BaseOptionType> , info: { index: number }) => React.ReactNode-5.11.0×
placeholder选择框默认文本ReactNode-×
placement选择框弹出的位置bottomLeft bottomRight topLeft topRightbottomLeft×
prefix自定义前缀ReactNode-5.22.0×
removeIcon自定义的多选框清除图标ReactNode<CloseOutlined />6.4.0
searchValue控制搜索文本string-×
showArrow是否显示箭头图标,请使用 suffixIcon={null} 替代booleantrue-×
showSearch配置是否可搜索boolean | Object单选为 false,多选为 trueObject: 6.0.06.4.0
size选择框大小large | medium | smallmedium×
status设置校验状态'error' | 'warning'-4.19.0×
styles用于自定义 Select 组件内部各语义化结构的行内 style,支持对象或函数Record<SemanticDOM, CSSProperties> | (info: { props }) => Record<SemanticDOM, CSSProperties>-5.25.0
suffixIcon自定义的选择框后缀图标。以防止图标被用于其他交互,替换的图标默认不会响应展开、收缩事件,可以通过添加 pointer-events: none 样式透传。ReactNode<DownOutlined />6.4.0
tagRender自定义 tag 内容 render,仅在 mode 为 multiple 或 tags 时生效(props) => ReactNode-×
labelRender自定义当前选中的 label 内容 render (LabelInValueType的定义见 LabelInValueType)(props: LabelInValueType) => ReactNode-5.15.0×
tokenSeparators自动分词的分隔符或自定义分词函数,仅在 mode="tags" 或 mode="multiple" 时生效string[] | ((input: string) => string[])-function: 6.5.0×
value指定当前选中的条目,多选时为一个数组。(value 数组引用未变化时,Select 不会更新)string | string[] | <br />number | number[] | <br />LabeledValue | LabeledValue[]-×
variant形态变体outlined | borderless | filled | underlinedoutlined5.13.0 | underlined: 5.24.05.19.0
virtual设置 false 时关闭虚拟滚动booleantrue4.1.0×
onActive键盘和鼠标交互时触发function(value: string | number | LabeledValue)-×
onBlur失去焦点时回调function-×
onChange选中 option,或 input 的 value 变化时,调用此函数function(value, option:Option | Array<Option>)-×
onClear清除内容时回调function-4.6.0×
onDeselect取消选中时调用,参数为选中项的 value (或 key) 值,仅在 multiple 或 tags 模式下生效function(value: string | number | LabeledValue)-×
onDropdownVisibleChange展开下拉菜单的回调,使用 onOpenChange 替换(open: boolean) => void-×
onOpenChange展开下拉菜单的回调(open: boolean) => void-×
onFocus获得焦点时回调(event: FocusEvent) => void-×
onInputKeyDown按键按下时回调(event: KeyboardEvent) => void-×
onPopupScroll下拉列表滚动时的回调(event: UIEvent) => void-×
onSearch文本框值变化时回调function(value: string)-×
onSelect被选中时调用,参数为选中项的 value (或 key) 值function(value: string | number | LabeledValue, option: Option)-×

注意,如果发现下拉菜单跟随页面滚动,或者需要在其他弹层中触发 Select,请尝试使用 getPopupContainer={triggerNode => triggerNode.parentElement} 将下拉弹层渲染节点固定在触发器的父元素中。

showSearch

参数说明类型默认值版本
autoClearSearchValue是否在选中项后清空搜索框,只在 mode 为 multiple 或 tags 时有效booleantrue
filterOption是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true,反之则返回 false。示例boolean | function(inputValue, option)true
filterSort搜索时对筛选结果项的排序函数, 类似Array.sort里的 compareFunction(optionA: Option, optionB: Option, info: { searchValue: string }) => number-searchValue: 5.19.0
optionFilterProp搜索时过滤对应的 option 属性,如设置为 children 表示对内嵌内容进行搜索。<br/> 若通过 options 属性配置选项内容,建议设置 optionFilterProp="label" 来对内容进行搜索。<br/> 当传入 string[] 时多个字段进行 OR 匹配搜索string | string[]valuestring[]: 6.1.0
searchValue控制搜索文本string-
onSearch文本框值变化时回调function(value: string)-
searchIcon自定义的搜索图标ReactNode<SearchOutlined />6.4.0

Select Methods

名称说明版本
blur()取消焦点
focus()获取焦点

Option props

参数说明类型默认值版本
classNameOption 器类名string-
disabled是否禁用booleanfalse
title选项上的原生 title 提示string-
value默认根据此属性值进行筛选string | number-

OptGroup props

参数说明类型默认值版本
keyKeystring-
label组名React.ReactNode-
classNameOption 器类名string-
title选项上的原生 title 提示string-

Semantic DOM

语义节点原生说明版本
root根元素,包含相对定位、行内 flex 布局、光标样式、过渡动画、边框等选择器容器的基础样式—
prefix前缀元素,包含前缀内容的布局和样式—
content多选容器,包含已选项的布局、间距、换行相关样式—
placeholder占位符元素,包含占位符文本的字体样式和颜色—
clear清除按钮元素,包含清除按钮的布局、样式和交互效果—
input输入框元素,包含搜索输入框的样式、光标控制、字体继承等搜索相关样式,去除了边框样式—
suffix后缀元素,包含后缀内容的布局和样式,如清除按钮、箭头图标等—
popup.root弹出菜单元素,包含弹出层的定位、层级、背景、边框、阴影等弹出容器样式—
popup.list弹出菜单列表元素,包含选项列表的布局、滚动、最大高度等列表容器样式—
popup.listItem弹出菜单条目元素,包含选项项的内边距、悬浮效果、选中状态、禁用状态等选项交互样式—
item多选项元素,包含边框、背景、内边距、外边距样式 (多选模式)—
itemContent多选项内容区域,包含文字的省略样式 (多选模式)—
itemRemove多选项移除按钮,包含字体相关样式 (多选模式)—

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

主题变量(Design Token)

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

令牌类型原生说明
zIndexPopupnumber下拉菜单 z-index
optionSelectedColorstring选项选中时文本颜色
optionSelectedFontWeightCSSProperties['fontWeight']选项选中时文本字重
optionSelectedBgstring选项选中时背景色
optionActiveBgstring选项激活态时背景色
optionPaddingCSSProperties['padding']选项内间距
optionFontSizenumber选项字体大小
optionLineHeightCSSProperties['lineHeight']选项行高
optionHeightnumber选项高度
selectorBgstring选框背景色
clearBgstring清空按钮背景色
singleItemHeightLGnumber单选大号回填项高度
showArrowPaddingInlineEndnumber箭头的行末内边距
hoverBorderColorstring悬浮态边框色
activeBorderColorstring激活态边框色
activeOutlineColorstring激活态 outline 颜色

声明来源: vendor/components/select/style/token.ts

import type { CSSProperties } from 'react';

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

export interface MultipleSelectorToken {
  /**
   * @desc 多选标签背景色
   * @descEN Background color of multiple tag
   */
  multipleItemBg: string;
  /**
   * @desc 多选标签边框色
   * @descEN Border color of multiple tag
   */
  multipleItemBorderColor: string;
  /**
   * @desc 多选标签高度
   * @descEN Height of multiple tag
   */
  multipleItemHeight: number;
  /**
   * @desc 小号多选标签高度
   * @descEN Height of multiple tag with small size
   */
  multipleItemHeightSM: number;
  /**
   * @desc 大号多选标签高度
   * @descEN Height of multiple tag with large size
   */
  multipleItemHeightLG: number;
  /**
   * @desc 多选框禁用背景
   * @descEN Background color of multiple selector when disabled
   */
  multipleSelectorBgDisabled: string;
  /**
   * @desc 多选标签禁用文本颜色
   * @descEN Text color of multiple tag when disabled
   */
  multipleItemColorDisabled: string;
  /**
   * @desc 多选标签禁用边框色
   * @descEN Border color of multiple tag when disabled
   */
  multipleItemBorderColorDisabled: string;
  /**
   * @internal
   */
}

export interface ComponentToken extends MultipleSelectorToken {
  /**
   * @desc 下拉菜单 z-index
   * @descEN z-index of dropdown
   */
  zIndexPopup: number;
  /**
   * @desc 选项选中时文本颜色
   * @descEN Text color when option is selected
   */
  optionSelectedColor: string;
  /**
   * @desc 选项选中时文本字重
   * @descEN Font weight when option is selected
   */
  optionSelectedFontWeight: CSSProperties['fontWeight'];
  /**
   * @desc 选项选中时背景色
   * @descEN Background color when option is selected
   */
  optionSelectedBg: string;
  /**
   * @desc 选项激活态时背景色
   * @descEN Background color when option is active
   */
  optionActiveBg: string;
  /**
   * @desc 选项内间距
   * @descEN Padding of option
   */
  optionPadding: CSSProperties['padding'];
  /**
   * @desc 选项字体大小
   * @descEN Font size of option
   */
  optionFontSize: number;
  /**
   * @desc 选项行高
   * @descEN Line height of option
   */
  optionLineHeight: CSSProperties['lineHeight'];
  /**
   * @desc 选项高度
   * @descEN Height of option
   */
  optionHeight: number;
  /**
   * @desc 选框背景色
   * @descEN Background color of selector
   */
  selectorBg: string;
  /**
   * @desc 清空按钮背景色
   * @descEN Background color of clear button
   */
  clearBg: string;
  /**
   * @desc 单选大号回填项高度
   * @descEN Height of single selected item with large size
   */
  singleItemHeightLG: number;
  /**
   * @desc 箭头的行末内边距
   * @descEN Inline end padding of arrow
   */
  showArrowPaddingInlineEnd: number;
  /**
   * @desc 悬浮态边框色
   * @descEN Hover border color
   */
  hoverBorderColor: string;
  /**
   * @desc 激活态边框色
   * @descEN Active border color
   */
  activeBorderColor: string;
  /**
   * @desc 激活态 outline 颜色
   * @descEN Active outline color
   */
  activeOutlineColor: string;
}

export interface SelectorToken {
  selectAffixPadding: number | string;
  inputPaddingHorizontalBase: number | string;
  multipleSelectItemHeight: number;
  selectHeight: number;
}

export interface SelectToken extends FullToken<'Select'>, SelectorToken {
  rootPrefixCls: string;

  /** @private Used for internal calculation */
  INTERNAL_FIXED_ITEM_MARGIN: number;
}

FAQ

mode="tags" 模式下为何搜索有时会出现两个相同选项?

这一般是 options 中的 label 和 value 不同导致的,你可以通过 optionFilterProp="label" 将过滤设置为展示值以避免这种情况。

点击 popupRender 里的元素,下拉菜单不会自动消失?

你可以使用受控模式,手动设置 open 属性:codesandbox。

反过来希望点击 popupRender 里元素不消失该怎么办?

Select 当失去焦点时会关闭下拉框,你可以通过阻止默认行为来避免丢失焦点导致的关闭:

<Select
  popupRender={() => (
    <div
      onMouseDown={(e) => {
        e.preventDefault();
        e.stopPropagation();
      }}
    >
      Some Content
    </div>
  )}
/>

自定义 Option 样式导致滚动异常怎么办?

这是由于虚拟滚动默认选项高度为 24px,如果你的选项高度小于该值则需要通过 listItemHeight 属性调整,而 listHeight 用于设置滚动容器高度:

<Select listItemHeight={10} listHeight={250} />

注意:listItemHeight 和 listHeight 为内部属性,如无必要,请勿修改该值。

为何无障碍测试会报缺失 aria- 属性?

Select 无障碍辅助元素仅在弹窗展开时创建,因而当你在进行无障碍检测时请先打开下拉后再进行测试。对于 aria-label 与 aria-labelledby 属性缺失警告,请自行为 Select 组件添加相应无障碍属性。

Select 虚拟滚动会模拟无障碍绑定元素。如果需要读屏器完整获取全部列表,你可以设置 virtual={false} 关闭虚拟滚动,无障碍选项将会绑定到真实元素上。

使用 tagRender 生成的自定义标签,点击关闭时会呼出下拉框

如果你不希望点击某个元素后下拉框自动出现(例如关闭按钮),可以在其上阻止 MouseDown 事件的传播。

<Select
  tagRender={(props) => {
    const { closable, label, onClose } = props;
    return (
      <span className="border">
        {label}
        {closable ? (
          <span
            onMouseDown={(e) => e.stopPropagation()}
            onClick={onClose}
            className="cursor-pointer"
          >
            ❎
          </span>
        ) : null}
      </span>
    );
  }}
/>

原生通用属性

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

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

安装并复现示例

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

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

原生类型参考

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

  • vendor/components/select/index.tsx
  • vendor/components/select/style/select-input.ts
  • vendor/components/select/style/token.ts
  • vendor/components/select/useIcons.tsx
  • vendor/components/select/usePopupRender.tsx

来源与许可

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

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