Select
通过搜索和多项选择从列表中进行选择。
何时使用
Select 允许您从列表中选择现成的值,并在标签模式下 - 创建字符串标签。当有很多选项或者通过签名搜索它们比在页面上不断显示它们更方便时使用它。
对于一些简短的选项,请考虑 Radio。如果用户必须输入带提示的自由文本,则需要 AutoComplete。 TreeSelect 和 Cascader 旨在从层次结构中进行选择。
在@woodger/antd中,单个Select存储字符串或数字,mode="multiple"存储相同类型的值的数组。 mode="tags" 模式另外创建字符串;数字 0 和字符串“0”仍然是不同的值。 options 是可选的,默认为空数组。
选择 CSS 前缀 显示全局 ConfigProvider.prefixCls 和本地 prefixCls,无需重置状态。控件、tags 和弹出窗口遵循 prefixCls。无论本地类和主题如何,服务变量都共享一个公共名称空间。保存打开的列表、搜索输入和选择。
含义、签名和清算
默认情况下,options 中的每个变体都包含一个唯一的 value 和一个文本 label。该值用于应用程序模型中,签名用于显示给用户。数字 0、数字 1 和字符串 "1" 保留其类型:通过 undefined 测试是否没有选择,而不是通过真值。
| 脚本 | 状态 | 工作示例 |
|---|---|---|
| 单选 | 字符串或数字 | 基本选择 |
| 多选 | 数组,mode="multiple" |
多项选择 |
| 获取标签 | 启用 labelInValue 后包含 value 和 label 的对象 |
值与标签 |
| 关联两个列表 | 更新选项和依赖值 | 关联列表 |
对于本地反应状态,请使用 bind:value。如果状态属于模型Form,则传递value并通过onValueChange更新模型。初始非受控值通过defaultValue设置;对此属性的后续更改不会重新初始化该字段。
allowClear 增加清洁。单个字段返回 undefined,多个字段返回 []。将此格式存储在处理程序中。在原生 FormData 中,值变成字符串;这不会改变反应模型类型。 如果值是稳定的机器代码而不是变量、函数、类或运行时名称,则
multiple 选择已有选项,tags 允许自由输入。labelInValue 将标签与值一起保存,详见选中标签。当前支持情况和剩余限制列在示例覆盖中。
标签和限制
标签通过 Enter、在列表中选择或 blur 来确认新选项。blur 修剪边缘周围的空白;转义保存未完成的输入。清除还会删除待处理的搜索。默认情况下,标签按 value 搜索;对于标签,设置 showSearch.optionFilterProp="label"。 autoClearSearchValue=false 在选择时保留本地搜索;托管行由所有者更新。
分离器 在 multiple/tags 中工作。 tokenSeparators 数组终止部分输入; multiple 接受现成的选项,tags 创建字符串。该函数接收整个字符串并可以规范空格。 IME 不会在合成过程中被解析。本机处理程序可以覆盖 paste/合成;应用程序中通常不需要额外的输入拦截。
maxCount 限制新选择的值。它不会修剪 defaultValue 或所有者数组。 maxTagCount 仅限制可见标签;值保存在模型、FormData 中并 reset。 数值限制 显示带有隐藏完整 label 的 maxTagPlaceholder。 responsive 测量浏览器中的宽度;使用SSR,所有值在测量前都是可见的。
maxTagTextLength 仅更改文本并添加“...”;保留完整的 label/title 和值。长度以 UTF-16 计算,没有代理对中断,但不根据字素簇计算。 tagRender 的 label 为 Snippet、value/index 和 onClose(常规标签)。摘要标签 isMaxTag=true,没有 value/index/onClose。 close 自己的控件应控制 mousedown,以免将弹出窗口作为附带事件打开。
optionRender 自定义选项的被动内容。SelectFlattenOption<value, optionType>.data 包含原始记录,label 的类型为 unknown。索引包含分组标题;groupOption=true 表示分组内的选项。渲染器仅用于选项,不用于标题。选择行为、选中标签和原生选项按钮仍由 Select 管理。不要将交互式控件放在选项按钮中。
本地和远程搜索
要使用现成的列表进行搜索,请启用 showSearch。标准的 single/multiple 过滤器按 tags、label - 按 value 搜索。 showSearch.optionFilterProp 通过 OR 接受一个或多个字段,如 姓名和电子邮件示例 中。本机 showSearch.filterOption 接收字符串和原始 option,并优先于字段选择。
搜索字符串和所选值是不同的状态。 showSearch.searchValue 控制搜索文本,showSearch.onSearch 报告用户输入,bind:value 或 onValueChange 指选择。 showSearch.filterSort 获取两个原始 option 和当前的 searchValue;对过滤结果(包括合成 tags)进行排序,而不更改所有者数组。 排序示例 首先显示名称开头的匹配项。
远程搜索时,选项已按数据源过滤。设置showSearch.filterOption=false,否则本地过滤器可能会重新隐藏接收到的记录。执行来自showSearch.onSearch处理程序的请求;该库不选择传输,也不添加去抖。
独立的 远程搜索示例 链接搜索、取消先前的请求、延迟响应保护、错误和重试。应用程序使用滚动 onPopupScroll 来滚动下一页。卸载后,该示例释放计时器并取消请求。
loading 显示等待。空输出和源错误是不同的情况:设置适当的 notFoundContent 并在需要时提供重播。 Select 会记住所选值的标签,因此新输出不应删除已做出的选择。
大小、variant 和可用性可通过 ConfigProvider 协调。使用 Select 设计令牌(design tokens)及其参考表调整主题,使用 classNames 和 styles 设置各部分样式。样式示例展示共享设置与局部修改。
打开列表
popupMatchSelectWidth 设置面板宽度:true 匹配字段宽度,false 按内容自适应,数字指定像素宽度。字段宽度始终是最小值,因此较小的数字不会缩窄面板。Select 面板宽度可比较这些选项。省略属性或传入 undefined 会继承 ConfigProvider.popupMatchSelectWidth;没有共用设置时使用 true。
调整宽度保留输入控件和选中值。首次打开后,无效的数值 CSS 宽度会保留上次接受的值,关闭后重新打开也一样。内部视口默认最多 256 px,面板的 padding 和 border 另行计算。窗口渲染与滚动设置见长列表。
placement 选择面板的首选角:bottomLeft、bottomRight、topLeft 或 topRight。默认为 bottomLeft,RTL 下为 bottomRight。Select 面板位置可切换四种位置,并保留已选值。空间不足时面板可能翻转。
ConfigProvider.popupOverflow 设置计算溢出时使用的区域:视口或文档区域。共用示例展示继承与显式重置。即使没有 getPopupContainer,面板也使用 fixed 原生 popover 显示在页面上层;DOM 父节点和字段状态保持不变。
open 控件可见性,包括通过 bind:open。 onOpenChange 报告请求:所有者可以接受或拒绝它。 开度控制 显示了这两种方法。open 本身的初始或外部更改不会触发回调或将焦点更改到该字段。
defaultOpen 仅指定初始状态,其性能不如 open。 初次开业 在挂载后使用:使用 SSR aria-expanded=false,不会创建 popup,不会调用 optionRender/getter。对 defaultOpen 的后续更改不会重新 open 列表。删除托管打开会返回关闭的非托管状态。
disabled 隐藏弹出窗口而不回调。重新启用后非托管列表仍保持关闭状态;由所有者传递 open=true 保存请求并再次显示列表。 single 的外部闭包清除了内部搜索,但托管的 searchValue 更改了所有者。值和 DOM 字段被保留。
当输出为空时,本地 notFoundContent=null、false 或空字符串会隐藏 popup,保留原始 open 和输入。数字 0 仍然可见。支持常规 RenderEmptyContent,包括 boolean 和 readonly 数组;options 出现后,列表变得可见。在表单中 reset 关闭 bind:open;明确转让的 open 权仍归所有者所有。
长列表与滚动
对于大量选项,Select 渲染可见窗口并测量行高。100000 个选项示例保留多选,并通过公共 ref 跳转到列表末尾。
listHeight 设置内部视口高度,0 表示不限制。面板的 padding 和 border 另行计算。listItemHeight 是测量前的行高估计,默认来自 token.controlHeight;0 会关闭窗口渲染。
要渲染完整选项 DOM,可以设置 virtual={false}。没有局部属性时,采用 ConfigProvider.virtual。显式传入 virtual={undefined} 会启用 default=true,包括 provider=false 的情况。popupMatchSelectWidth=false 也会关闭虚拟化,数值 0 则保留虚拟化。
bind:this 提供 SelectRef:focus 和 blur 控制编辑器焦点,scrollTo(50000) 按索引滚动,包括当前窗口之外的行。索引包含分组标题。按 key 滚动时,请在原始记录中设置 key;缺省时先使用原始 value 字段,再使用自动生成的键。fieldNames.value 的映射不改变此规则。scrollTo({ top: 0 }) 按 px 设置位置。按 index/key 跳转在打开列表并通过 tick 更新 DOM 后执行,示例展示了这一过程。
onActive 单独报告当前活动值或 null,不代表选中模型变化。滚动时,onPopupScroll 接收内部视口的原生事件,currentTarget 和 this 都指向这个 div。
分组与原始记录
要按类别组织选项,可以像分组示例一样传入一层分组。标题不可选择;键盘导航跳过标题和禁用选项。匹配分组名称时可以保留其全部子项。
应用记录使用其他字段名时,fieldNames 将 value、label、options 和 groupLabel 映射到相应字段。原始记录字段展示数字编码、标签和分组,无需预先转换为 value/label。SelectProps<Value, Mode, OptionType> 的第三个参数指定记录类型;选中模型仍为字符串、数字或这些值的数组。空字段名采用标准名称,groupLabel 默认使用解析后的 label 字段。
onChange 报告选中值的变化,并提供记录的浅拷贝或浅拷贝数组。附加字段保留。原始记录中不存在 value/label 字段时,回调也不会添加这些字段。onSelect 在每次选择时调用,包括单选中重复选择同一项;onDeselect 在 multiple/tags 移除单个值时调用。全部清除时先调用 onClear,再调用 onChange,不产生 onDeselect。bind:value 和 onValueChange 继续连接模型。
已经显示的选中记录离开当前结果后仍保存在缓存中,直到取消选择。应用可以隐藏已选选项,同时保留标签和回调数据。value 重复时,使用当前数据映射中的最后一条记录。
对于没有原始记录的自由标签,onSelect 和 onDeselect 接收 {},onChange 接收的记录数组中也会包含该对象。tags 模式的类型涵盖这种情况,读取字段前请确认其值已定义。
水果示例会立即从 options 中移除所选记录。标签仍显示原名称,取消选择时 onDeselect 收到包含货号的原始记录。
原始选项的 title、className、style 和支持的 DOM/data-/aria-* 属性传递到列表元素。style 接受 CSS 对象或原生 CSS 字符串;分组标题使用 className、title 和标签。分组示例通过 fontWeight 突出 Svelte,并设置自定义 data 属性。
filterOption 接收原始选项或分组的浅拷贝。filterSort 对分组及其标准 options 字段排序;fieldNames 重命名子项字段时,由应用预先排列这些分组内的顺序。
选中值的标签
labelInValue 将模型改为 { value, label },multiple/tags 模式使用此类对象的数组。使用方显式提供的标签优先;undefined 从 optionLabelProp 或 fieldNames 指定的 label 字段读取。顶层 null 清空选择。显式指定类型时,使用 Select<Value, Mode, OptionType, true> 和 SelectLabelValue<Value>;前三个参数保持原有含义。
标签布局在 options 中使用真正的 Svelte snippets。optionLabelProp 为选中标签选择独立字段;使用 showSearch.optionFilterProp 单独配置按此字段过滤。富内容不会转为编辑器文本。
labelRender 接收 label、value、key、disabled 和 title,返回文本、内容数组或 Snippet。key 等于原始 value。函数也会在 SSR 时运行,必须保持纯函数。null/undefined 回退到原始值;false 和空字符串保留空标签。示例中,不可用记录仍在模型和 FormData 中保留数字 ID。
onChange 传递当前转换产生的标签;onSelect/onDeselect 使用原始记录的 fieldNames.label,不受 optionLabelProp 和 labelRender 影响。删除标签时,onChange 可能传递其余标签经 labelRender 渲染后的内容。FormData 始终包含原始值。标签可能是 Snippet 或其他内容,在当作字符串使用前应检查其类型。
自定义面板与样式
附加操作使用 popupRender:纯函数接收原始菜单 Snippet 并返回内容。带 origin 参数的 Snippet 可渲染菜单并添加相邻元素。按钮的 mousedown 处理保留编辑器焦点;交互元素放在选项按钮之外。
popupRender 在面板关闭时也运行,包括 SSR。内容在首次打开后挂载,关闭后保留状态;关闭期间提供的新 renderer 在下次打开时采用。null/undefined/false 或空字符串保留空面板。如果没有渲染原始菜单,方向键和 Enter 不选择选项,Escape 也不关闭此面板;blur 和外部点击保持通常行为。自定义面板隔离 FormItem status/feedback 和 Compact,同时保留 Form disabled/variant。
语义样式通过 classNames/styles 对象或接收 props 的纯函数设置。可用部分包括 root、prefix、suffix、input、placeholder、content、item、itemContent、itemRemove、clear 和 popup.root/list/listItem。prefix 提供编辑器前的内容;包括 0 在内的假值标量不创建节点。rootClassName 应用于 control 和面板。style 对象设置控件样式;原有 class 和 CSS 字符串 style 仍用于外层容器。
ConfigProvider.select 提供 variant、class/style、classNames/styles、showSearch、图标,以及 boolean 或对象形式的 allowClear。局部值优先;嵌套 provider 显式提供的 select 会替换父记录。类名合并,控件样式分层应用,局部 popup leaf 完整替换对应的 provider leaf。例如,局部 popup.root 不逐项继承共享 popup.root 的 CSS 属性。
图标与无障碍清除
图标示例结合 ConfigProvider.select 的共享配置和局部 suffix。loadingIcon 设置加载图标,showSearch.searchIcon 设置可搜索字段展开时的图标,menuItemSelectedIcon 设置选项标记,removeIcon 设置普通标签的删除图标。局部配置优先。
suffix 替换整个尾部区域,包括 Form 的反馈内容。函数接收 SelectSuffixInfo:searchValue、open、focused、showSearch 和 loading。返回 null/undefined 时使用默认尾部内容。suffix、menuItemSelectedIcon 和 removeIcon 的函数必须是纯函数,因为 SSR 和列表关闭时也会调用它们。要将 snippet 用作内容,可从函数返回它或将其放入数组;loadingIcon、searchIcon 和 clearIcon 可直接接收 snippet。
allowClear 接受 boolean 或包含 clearIcon 和 label 的对象。使用对象时,请提供已翻译的无障碍名称 label;缺省名称为“clear”。boolean true 保留默认的本地化名称。当前 Ant Design 文档中的 disabled 和 tabIndex 清除配置字段尚未提供。
自定义编辑器与字段
标签编辑器通过 components.input 替换标准字段内部的编辑器,同时保留选择、multiple/tags、自适应标签折叠和 tagRender。Snippet 接收 SelectInputContext:将 attributes 传给编辑器,并通过 Svelte attachment 连接 register。元素移除时会释放注册。bind:this 提供已注册编辑器的 focus 和 blur 方法。
完整字段替换使用 components.root 和 SelectRootContext。Root 替换整个字段:不再输出默认编辑器、标签、prefix、suffix 和清除按钮,并忽略 components.input。应用负责自定义字段的内容和样式。在 root 中输入文本不会自动更新 Select 的搜索内容或模型。
编辑器自身的 props 优先于生成的 attributes,root 的优先级相反。因此,仅传入确实需要覆盖的参数。rootElement 和 EditorElement 指定注册元素的类型;bind:nativeElement 和 bind:inputElement 在挂载后返回对应元素。扩展替换 API 尚未完整移植;示例展示的是已支持的场景,并不表示与 React 完全兼容。
示例
主要选择
单选、disabled、loading 和 allowClear。该值通过 bind:value 与模型关联。
<script lang="ts">
import { Select } from '@woodger/antd';
let value = $state<string | undefined>('lucy');
const options = [
{ value: 'jack', label: 'Jack' },
{ value: 'lucy', label: 'Lucy' },
{ value: 'disabled', label: "不可用的选项", disabled: true },
{ value: 'yiminghe', label: 'Yiminghe' }
];
</script>
<style>
.example {
display: grid;
gap: 20px;
}
.fields {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
output { color: var(--ant-color-text-secondary); }
@media (max-width: 560px) { .fields { grid-template-columns: minmax(0, 1fr); } }
</style>
<div class="example">
<div class="fields">
<Select options={(options)} bind:value aria-label={("基本选择")} />
<Select options={(options)} defaultValue="lucy" disabled aria-label={("不可用 选择")} />
<Select options={(options)} defaultValue="lucy" loading aria-label={("加载选择")} />
<Select options={(options)} defaultValue="lucy" allowClear aria-label={("可清除选择")} />
</div>
<output aria-label={("基础选择值")}>{(value ?? 'undefined')}</output>
</div>
在列表中搜索
showSearch 启用按名称搜索,showAction 使列表在获得焦点时打开。可使用方向键、Enter 和 Escape 操作列表。
<script lang="ts">
import { Select } from '@woodger/antd';
let value = $state<string>();
const options = ['Jack', 'Lucy', 'Tom'].map(label => ({ value: label, label }));
</script>
<style>
.example {
display: grid;
gap: 20px;
}
output { color: var(--ant-color-text-secondary); }
</style>
<div class="example">
<Select
options={(options)}
bind:value
showSearch
showAction={['focus']}
allowClear
placeholder={("寻找会员")}
aria-label={("在选择中搜索")}
/>
<output aria-label={("搜索结果 选择")}>{(value
?? ("未选择任何内容"))}</output>
</div>
自定义过滤
showSearch 对象中的 filterOption 按名称的开头进行搜索,而不是按子字符串的出现位置进行搜索。
<script lang="ts">
import { Select } from '@woodger/antd';
const options = ['Apple', 'Apricot', 'Pear', 'Pineapple'].map(label => ({ value: label, label }));
</script>
<Select
options={(options)}
aria-label={("按标题开头搜索")}
placeholder={("输入标题的开头")}
showSearch={{
filterOption: (search, option) =>
option.label.toLowerCase().startsWith(search.toLowerCase())
}}
/>
按多个字段搜索
showSearch.optionFilterProp 按 label 和电子邮件搜索源 options。
<script lang="ts">
import { Select } from '@woodger/antd';
const people = [
{ id: 0, name: "安娜", email: 'anna@example.test' },
{ id: 1, name: "鲍里斯", email: 'boris@example.test' },
{ id: 2, name: "信仰", email: 'vera@example.test' }
];
const options = people.map(person => ({
value: person.id,
label: person.name,
email: person.email
}));
</script>
<Select
options={(options)}
aria-label={("按姓名或电子邮件搜索")}
placeholder={("姓名或电子邮件")}
showSearch={{ optionFilterProp: ['label', 'email'] }}
/>
多项选择
mode="multiple" 绑定现成值的数组。可以删除或完全清除所选项目。
<script lang="ts">
import { Select } from '@woodger/antd';
let value = $state<string[]>(['a', 'c']);
const options = [
{ value: 'a', label: "开发" },
{ value: 'b', label: "设计" },
{ value: 'c', label: "分析" },
{ value: 'd', label: "档案", disabled: true }
];
</script>
<style>
.example {
display: grid;
gap: 20px;
}
output {
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
<div class="example">
<Select
options={(options)}
mode="multiple"
bind:value
allowClear
aria-label={("多项选择")}
placeholder={("选择团队")}
/>
<output aria-label={("选择阵列")}>{JSON.stringify(value)}</output>
</div>
三种尺寸
large、medium、small。如果没有本地 size,ConfigProvider.componentSize 是有效的。
<script lang="ts">
import { Select } from '@woodger/antd';
const options = ['Jack', 'Lucy', 'Tom'].map(label => ({ value: label, label }));
const sizes = ['large', 'medium', 'small'] as const;
</script>
<style>
.example {
display: grid;
gap: 20px;
}
</style>
<div class="example">
{#each sizes as size (size)}
<Select options={(options)} {size} defaultValue="Lucy" aria-label={("选择尺码 " + String((size)) + "")} />
{/each}
</div>
排序搜索
showSearch.filterSort 对结果进行排序:首先匹配名称开头的内容,然后是字母表。
<script lang="ts">
import { Select } from '@woodger/antd';
const options = ['React', 'Preact', 'Svelte', 'Angular'].map(label => ({ value: label, label }));
</script>
<Select
options={(options)}
aria-label={("排序搜索")}
placeholder={("尝试重新")}
showSearch={{
filterSort: (left, right, { searchValue }) => {
const query = searchValue.toLowerCase();
const prefix = Number(!left.label.toLowerCase().startsWith(query))
- Number(!right.label.toLowerCase().startsWith(query));
return prefix || left.label.localeCompare(right.label);
}
}}
/>
选项组
分组、按标签搜索、禁用选项及重复的 onSelect 事件。
<script lang="ts">
import { Select } from '@woodger/antd';
const options = [
{
label: "开发",
options: [
{
value: 'svelte',
label: 'Svelte',
title: 'Svelte 5',
className: 'framework-option',
style: { fontWeight: 600 },
'data-technology': 'svelte'
},
{ value: 'typescript', label: 'TypeScript' }
]
},
{
label: "设计",
options: [
{ value: 'figma', label: 'Figma' },
{ value: 'sketch', label: 'Sketch', disabled: true }
]
}
];
let value = $state<string | undefined>('svelte');
let selections = $state(0);
</script>
<style>
.example {
display: grid;
gap: 12px;
min-width: 0;
}
output {
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
<div class="example">
<Select
options={(options)}
bind:value
showSearch={{ optionFilterProp: 'label' }}
onSelect={() => { selections += 1; }}
aria-label={("带分组的 Select")}
style="width:100%"
/>
<output aria-label={("分组 Select 的选中值")}>{value ?? '—'}</output>
<output aria-label={("Select 选择次数")}>
{("选择次数: ")}{selections}
</output>
</div>
原始记录字段
fieldNames 将记录字段映射到 Select,回调返回原始数据。
<script lang="ts">
import { Button, Select } from '@woodger/antd';
interface Person {
key: string;
code?: number;
caption?: string;
department?: string;
members?: readonly Person[];
profile?: { email: string };
}
const PeopleSelect = Select<number, 'multiple', Person>;
const groups: readonly Person[] = [
{
key: 'engineering',
department: ("开发"),
members: [
{
key: 'anna',
code: 0,
caption: ("安娜"),
profile: { email: 'anna@example.com' }
},
{
key: 'boris',
code: 1,
caption: ("鲍里斯"),
profile: { email: 'boris@example.com' }
}
]
},
{
key: 'design',
department: ("设计"),
members: [
{
key: 'elena',
code: 2,
caption: ("埃琳娜"),
profile: { email: 'elena@example.com' }
}
]
}
];
let value = $state<number[]>([0]);
let hidden = $state<number[]>([]);
let events = $state<string[]>([]);
const options = $derived(groups.map(group => ({
...group,
members: group.members?.filter(person =>
person.code === undefined || !hidden.includes(person.code)
)
})));
function record(
event: 'change' | 'select' | 'deselect' | 'clear',
next?: number | number[],
option?: Person | Person[]
) {
const entry = JSON.stringify({ event, value: next, option });
events = [...events.slice(-5), entry];
}
</script>
<style>
.example {
display: grid;
gap: 16px;
min-width: 0;
}
.actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
output {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
<div class="example">
<PeopleSelect
{options}
bind:value
mode="multiple"
fieldNames={{ value: 'code', label: 'caption', options: 'members', groupLabel: 'department' }}
showSearch={{ optionFilterProp: ['caption', 'department'] }}
allowClear
onChange={(next, option) => record('change', next, option)}
onSelect={(next, option) => record('select', next, option)}
onDeselect={(next, option) => record('deselect', next, option)}
onClear={() => record('clear')}
aria-label={("使用记录字段的 Select")}
style="width:100%"
/>
<div class="actions">
<Button disabled={value.length === 0} onclick={() => { hidden = [...value]; }}>
{("隐藏已选记录")}
</Button>
<Button disabled={hidden.length === 0} onclick={() => { hidden = []; }}>
{("恢复全部记录")}
</Button>
<Button onclick={() => { events = []; }}>{("清空 Select 日志")}</Button>
</div>
<output
aria-label={("Select 已选记录编码")}
>{JSON.stringify(value)}</output>
<output aria-label={("携带自定义数据的 Select 事件")}>
{events.join('\n') || '—'}
</output>
</div>
相关列表
更改国家/地区会更新可用城市并重置应用程序处理程序中的相关值。
<script lang="ts">
import { Select, type SelectOption } from '@woodger/antd';
const cities = {
ru: [{ value: 'moscow', label: "莫斯科" }, { value: 'kazan', label: "喀山" }],
fr: [{ value: 'paris', label: "巴黎" }, { value: 'lyon', label: "里昂" }]
};
let country = $state<'ru' | 'fr'>('ru');
let city = $state('moscow');
const countries: SelectOption<'ru' | 'fr'>[] = [
{ value: 'ru', label: "俄罗斯" }, { value: 'fr', label: "法国" }
];
</script>
<style>
.example {
display: grid;
gap: 20px;
}
output { color: var(--ant-color-text-secondary); }
</style>
<div class="example">
<Select aria-label={("国家选择")} value={country} options={(countries)} onValueChange={value => {
if (!value) {
return;
}
country = value;
city = cities[value][0].value;
}} />
<Select
aria-label={("城市选择")}
options={(cities[country])}
bind:value={city}
/>
<output aria-label={("相关选择值")}>{country} / {city}</output>
</div>
含义和签名
labelInValue 返回包含 value 和 label 的对象。数字 ID 0 保持其类型。
<script lang="ts">
import { Select, type SelectLabelValue } from '@woodger/antd';
interface Plan {
value: number;
label: string;
}
const PlanSelect = Select<number, undefined, Plan, true>;
const MultiplePlanSelect = Select<number, 'multiple', Plan, true>;
const options = [{ value: 0, label: "根据" }, { value: 1, label: "命令" }];
let value = $state<SelectLabelValue<number> | undefined>({
value: 0,
label: ("根据")
});
let plans = $state<SelectLabelValue<number>[]>([]);
</script>
<style>
.example {
display: grid;
gap: 20px;
}
output {
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
<div class="example">
<PlanSelect
options={(options)}
bind:value
labelInValue
allowClear
aria-label={("接收选择签名")}
/>
<output
aria-label={("选择含义和签名")}
>{JSON.stringify(value ?? {})}</output>
<MultiplePlanSelect
options={(options)}
bind:value={plans}
labelInValue
mode="multiple"
allowClear
aria-label={("Select 多选对象")}
/>
<output aria-label={("Select 标签值数组")}>
{JSON.stringify(plans)}
</output>
</div>
标签布局与文本
Svelte snippets 渲染选项;optionLabelProp 为控件选择单独的标签。
<script lang="ts">
import { Select, Checkbox } from '@woodger/antd';
let value = $state<string>('svelte');
let plainLabel = $state(true);
const options = $derived([
{ value: 'svelte', label: svelteLabel, caption: 'Svelte 5' },
{ value: 'typescript', label: typescriptLabel, caption: 'TypeScript' }
]);
</script>
<style>
.example {
display: grid;
gap: 16px;
}
.label {
display: inline-flex;
align-items: baseline;
gap: 8px;
}
small, output { color: var(--ant-color-text-secondary); }
</style>
{#snippet svelteLabel()}
<span class="label" data-rich-label="svelte">
<strong>Svelte</strong><small>{("反应式接口")}</small>
</span>
{/snippet}
{#snippet typescriptLabel()}
<span class="label" data-rich-label="typescript">
<strong>TypeScript</strong><small>{("类型检查")}</small>
</span>
{/snippet}
<div class="example">
<Checkbox bind:checked={plainLabel}>
{("选中选项使用文本标签")}
</Checkbox>
<Select
{options}
bind:value
optionLabelProp={plainLabel ? 'caption' : undefined}
showSearch={{ optionFilterProp: 'caption' }}
aria-label={("富标签的 Select")}
/>
<output aria-label={("富标签 Select 的值")}>{value}</output>
</div>
自定义选中标签
labelRender 说明记录缺失,同时保留原始模型和表单值。
<script lang="ts">
import { Button, Select, type SelectLabelRenderInfo } from '@woodger/antd';
const NumberSelect = Select<number>;
const options = [{ value: 0, label: "根据" }, { value: 1, label: "命令" }];
let value = $state<number | undefined>(42);
function renderLabel(info: SelectLabelRenderInfo<number>) {
return typeof info.label === 'string' ? info.label : missingLabel;
}
</script>
<style>
.example {
display: grid;
gap: 16px;
}
.missing {
display: inline-flex;
gap: 8px;
}
small, output { color: var(--ant-color-text-secondary); }
</style>
{#snippet missingLabel()}
<span class="missing" data-missing-label>
<strong>№ {value}</strong><small>{("记录不可用")}</small>
</span>
{/snippet}
<form class="example">
<NumberSelect
options={(options)}
bind:value
labelRender={renderLabel}
name="plan"
aria-label={("自定义选中标签的 Select")}
/>
<Button onclick={() => { value = 42; }}>{("显示缺失的记录")}</Button>
<output aria-label={("自定义标签 Select 的值")}>{value}</output>
</form>
下拉列表中的附加操作
popupRender 保留默认菜单,并在不丢失编辑器焦点的情况下添加操作。
<script lang="ts">
import type { Snippet } from 'svelte';
import { Button, Divider, Select } from '@woodger/antd';
let value = $state<string>();
let added = $state(0);
let options = $state([{ value: 'first', label: ("第一个选项") }]);
function addOption() {
added += 1;
const label = ("" + String((added)) + ". 新选项");
options = [...options, { value: `new-${added}`, label }];
}
</script>
<style>
.footer {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
}
output {
display: block;
margin-top: 12px;
color: var(--ant-color-text-secondary);
}
</style>
{#snippet popupContent(origin: Snippet)}
{@render origin()}
<Divider style="margin: 8px 0;" />
<div class="footer">
<Button
type="text"
onmousedown={event => { event.preventDefault(); }}
onclick={addOption}
>{("添加选项")}</Button>
<span>{added}</span>
</div>
{/snippet}
<Select
{options}
bind:value
popupRender={() => popupContent}
aria-label={("附加操作的 Select")}
/>
<output aria-label={("自定义 Select 面板的选择")}>{value ?? '—'}</output>
Select 各部分样式
Prefix、classNames 和 styles 补充 ConfigProvider.select 共享设置。
<script lang="ts">
import { Checkbox, ConfigProvider, Select } from '@woodger/antd';
let value = $state<string | undefined>('reader');
let warning = $state(false);
const options = [{ value: 'reader', label: "读者" }, { value: 'editor', label: "编辑" }];
</script>
<style>
.example {
display: grid;
gap: 16px;
}
output { color: var(--ant-color-text-secondary); }
</style>
<div class="example">
<Checkbox bind:checked={warning}>{("警告状态")}</Checkbox>
<ConfigProvider select={{
allowClear: true,
showSearch: true,
classNames: { root: 'shared-select', popup: { root: 'shared-select-popup' } },
styles: { root: { borderRadius: 12 }, popup: { root: { borderRadius: 12 } } }
}}>
<Select
options={(options)}
bind:value
prefix={("角色")}
status={warning ? 'warning' : undefined}
rootClassName="role-select"
classNames={({ props }) => ({ root: props.status === 'warning' ? 'role-warning' : '' })}
styles={{
prefix: { color: 'var(--ant-color-text-secondary)' },
popup: { listItem: { paddingInline: 16 } }
}}
aria-label={("语义样式的 Select")}
/>
</ConfigProvider>
<output aria-label={("已设置样式的 Select 值")}>{value ?? '—'}</output>
</div>
图标与清除
ConfigProvider.select 提供共享图标和清除配置;局部 suffix 显示字段状态。
<script lang="ts">
import { Checkbox, ConfigProvider, Select, type SelectSuffixInfo } from '@woodger/antd';
const options = ['Svelte', 'TypeScript', 'CSS'].map(label => ({ value: label, label }));
let values = $state(['Svelte']);
let value = $state<string | undefined>('TypeScript');
let loading = $state(false);
</script>
<style>
.example {
display: grid;
gap: 16px;
}
.fields {
display: grid;
gap: 12px;
}
svg {
display: block;
width: 1em;
height: 1em;
}
.spinner { animation: spin 1s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }
</style>
{#snippet searchIcon()}
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" aria-hidden="true">
<circle cx="6.5" cy="6.5" r="4.5" /><path d="m10 10 4 4" />
</svg>
{/snippet}
{#snippet loadingIcon()}
<svg class="spinner" viewBox="0 0 16 16" fill="none" stroke="currentColor" aria-hidden="true">
<path d="M8 2a6 6 0 1 1-6 6" />
</svg>
{/snippet}
{#snippet arrow()}
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" aria-hidden="true">
<path d="m3 6 5 5 5-5" />
</svg>
{/snippet}
<div class="example">
<Checkbox bind:checked={loading}>{("显示加载中")}</Checkbox>
<ConfigProvider select={{
loadingIcon,
showSearch: { searchIcon },
menuItemSelectedIcon: ({ isSelected }) => isSelected ? '✓' : null,
removeIcon: '−',
allowClear: { clearIcon: '×', label: ("清除技术选项") }
}}>
<div class="fields">
<Select
mode="multiple"
{options}
bind:value={values}
{loading}
aria-label={("带自定义图标的技术选项")}
/>
<Select
{options}
bind:value
{loading}
allowClear={{ label: ("清除主要语言") }}
suffix={(info: SelectSuffixInfo) => {
if (info.loading) {
return loadingIcon;
}
return info.open ? searchIcon : arrow;
}}
aria-label={("带自定义尾部内容的主要语言")}
/>
</div>
</ConfigProvider>
</div>
自定义标签编辑器
components.input 保留标签和自适应折叠。Register 将编辑器连接到 Select 的焦点和键盘处理。
<script lang="ts">
import {
Button, Select, Tag, type SelectInputContext, type SelectRef, type SelectTagInfo
} from '@woodger/antd';
const options = ['Svelte', 'TypeScript', 'JavaScript', 'HTML', 'CSS']
.map(label => ({ value: label, label }));
let values = $state(['Svelte', 'TypeScript', 'HTML']);
let width = $state(480);
let control = $state<SelectRef>();
</script>
<style>
.example {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 12px;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
output { overflow-wrap: anywhere; }
</style>
{#snippet editor({ attributes, register }: SelectInputContext)}
<input {...attributes} {@attach register} />
{/snippet}
{#snippet tag(info: SelectTagInfo<string>)}
<Tag
color={info.isMaxTag ? undefined : 'blue'}
closable={info.closable}
disabled={info.disabled}
onClose={info.onClose}
closeLabel={`${("删除标签")} ${info.value}`}
style="margin-inline-end: 4px"
onmousedown={event => {
event.preventDefault();
event.stopPropagation();
}}
>{@render info.label()}</Tag>
{/snippet}
<div class="example">
<div class="controls">
<Button onclick={() => { width = 220; }}>{("视野狭窄")}</Button>
<Button onclick={() => { width = 480; }}>{("宽视野")}</Button>
<Button onclick={() => control?.focus()}>{("聚焦编辑器")}</Button>
</div>
<div style={`
width: ${width}px;
max-width: 100%;
`}>
<Select
mode="tags"
{options}
bind:value={values}
bind:this={control}
components={{ input: { render: editor, props: { style: { fontFamily: 'monospace' } } } }}
maxTagCount="responsive"
tagRender={tag}
aria-label={("自定义编辑器中的标签")}
/>
</div>
<output aria-label={("自定义编辑器的值")}>
{JSON.stringify(values)}
</output>
</div>
替换整个字段
components.root 将字段替换为按钮;应用提供按钮文本和样式,Select 管理列表。
<script lang="ts">
import { Button, Select, type SelectRootContext } from '@woodger/antd';
const options = [{ value: 'reader', label: "读者" }, { value: 'editor', label: "编辑" }];
let value = $state<string | undefined>('reader');
let open = $state(false);
let root = $state<HTMLButtonElement | HTMLDivElement>();
const selected = $derived(options.find(option => option.value === value));
const label = $derived(selected?.label ?? "选择角色");
</script>
<style>
.example {
display: grid;
gap: 12px;
}
.trigger {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
width: 100%;
padding: 8px 12px;
font: inherit;
cursor: pointer;
color: var(--ant-color-text);
background: var(--ant-color-bg-container);
border: 1px solid var(--ant-color-border);
border-radius: var(--ant-border-radius);
}
.trigger:focus-visible {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
</style>
{#snippet field({ attributes, register }: SelectRootContext<HTMLButtonElement>)}
<button
{...attributes}
type="button"
class="trigger"
aria-haspopup="listbox"
aria-expanded={open}
{@attach register}
>
{(label)}<span aria-hidden="true">⌄</span>
</button>
{/snippet}
<div class="example">
<Select
options={(options)}
bind:value
bind:open
bind:nativeElement={root}
components={{ root: field }}
showSearch={false}
aria-label={("通过自定义字段选择角色")}
/>
<Button onclick={() => root?.focus()}>{("聚焦自定义字段")}</Button>
</div>
远程搜索
具有延迟、旧请求取消、页面、错误和重试的演示源。更改问题时会保存选定的签名。
<script lang="ts">
import { onMount } from 'svelte';
import { Button, Select, type SelectOption } from '@woodger/antd';
const people = Array.from({ length: 40 }, (_, index) => ({
value: index,
label: `参加者 ${String(index + 1).padStart(2, '0')}`
}));
let selected = $state<number[]>([]);
let options = $state<SelectOption<number>[]>([]);
let search = $state('');
let loading = $state(false);
let error = $state('');
let total = $state(0);
let alive = false;
let failNext = false;
let request = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const hasMore = $derived(options.length < total);
function load(query: string, more = false) {
if (!alive || more && loading) {
return;
}
clearTimeout(timer);
const current = ++request;
const offset = more ? options.length : 0;
search = query;
loading = true;
error = '';
if (!more) options = [];
timer = setTimeout(() => {
if (!alive || current !== request) {
return;
}
loading = false;
if (failNext) {
failNext = false;
error = ("加载成员失败。");
return;
}
const matches = people.filter(person => person.label.toLowerCase().includes(
query.toLowerCase()
));
total = matches.length;
options = [...(more ? options : []), ...matches.slice(offset, offset + 8)];
}, 250);
}
onMount(() => {
alive = true;
load('');
return () => {
alive = false;
request += 1;
clearTimeout(timer);
};
});
</script>
<style>
.example {
display: grid;
gap: 20px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
output {
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
.error {
margin: 0;
color: var(--ant-color-error);
}
</style>
{#snippet empty()}<span role="status">{loading ? ("正在加载参与者...") : (error
|| ("没有找到会员"))}</span>{/snippet}
<div class="example">
<Select
options={(options)}
mode="multiple"
bind:value={selected}
aria-label={("远程搜索选择")}
showSearch={{ searchValue: search, onSearch: value => load(value), filterOption: false }}
{loading}
status={error ? 'error' : undefined}
notFoundContent={(empty)}
allowClear
placeholder={("寻找会员")}
onPopupScroll={event => {
const list = event.currentTarget;
if (hasMore && list.scrollTop + list.clientHeight >= list.scrollHeight - 16) {
load(search, true);
}
}}
/>
<div class="actions">
<Button disabled={!hasMore || loading} onclick={() => load(search, true)}>
{("更多精选会员")}
</Button>
<Button onclick={() => {
failNext = true;
load(search);
}}>{("模拟选择错误")}</Button>
{#if error}<Button
onclick={() => load(search)}
>{("重复选择请求")}</Button>{/if}
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<output
aria-label={("选定会员 选择")}
>{JSON.stringify(selected)}</output>
</div>
隐藏选定的选项
从 options 移除选项后,所选标签保留原名称,onDeselect 仍收到原始记录。
<script lang="ts">
import { Select } from '@woodger/antd';
let selected = $state<string[]>([]);
let removed = $state('');
const source = [
{ value: 'apple', label: "苹果", sku: 'A-01' },
{ value: 'pear', label: "梨", sku: 'P-02' },
{ value: 'orange', label: "橙子", sku: 'O-03' }
];
const options = $derived(source.filter(option => !selected.includes(option.value)));
</script>
<style>
.example {
display: grid;
gap: 20px;
}
output {
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
<div class="example">
<Select options={(options)} bind:value={selected} mode="multiple" allowClear
onDeselect={(_, option) => removed = option.sku}
aria-label={("隐藏选定的选项")} notFoundContent={("已选择所有选项")} />
<output aria-label={("隐藏选择选项")}>{JSON.stringify(selected)}</output>
{#if removed}
<output aria-label={("原始记录")}>{removed}</output>
{/if}
</div>
设计选项
四个 single/multiple 选项以及从ConfigProviderfilled 的通用继承。
<script lang="ts">
import { Checkbox, ConfigProvider, Select } from '@woodger/antd';
import type { Variant } from '@woodger/antd';
const variants: readonly Variant[] = ['outlined', 'filled', 'borderless', 'underlined'];
const options = [{ value: 'anna', label: "安娜" }, { value: 'boris', label: "鲍里斯" }];
let explicit = $state(true);
let value = $state<string | undefined>('anna');
let values = $state<string[]>(['anna']);
</script>
<style>
.settings { margin-bottom: 24px; }
.examples {
display: grid;
gap: 24px;
}
.row {
display: grid;
gap: 8px;
min-width: 0;
}
.pair {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
</style>
<div
class="settings"
><Checkbox
bind:checked={explicit}
>{("本地选择选项")}</Checkbox></div>
<ConfigProvider variant="filled">
<div class="examples">
{#each variants as variant (variant)}
<div class="row">
<span>{(variant)}</span>
<div class="pair">
<Select options={(options)} bind:value variant={explicit
? variant
: undefined}
aria-label={("单选 " + String((variant)) + "")} />
<Select
options={(options)}
mode="multiple"
bind:value={values}
variant={explicit ? variant : undefined}
aria-label={("多项选择 " + String((variant)) + "")}
/>
</div>
</div>
{/each}
</div>
</ConfigProvider>
错误和警告
status 显示 error 或 warning;该错误也由 aria-invalid 指示。
<script lang="ts">
import { Select } from '@woodger/antd';
const options = ['Jack', 'Lucy', 'Tom'].map(label => ({ value: label, label }));
</script>
<style>
.example {
display: grid;
gap: 20px;
}
</style>
<div class="example">
<Select options={(options)} status="error" aria-label={("选择错误")} placeholder={("更正选择")} />
<Select options={(options)} status="warning" aria-label={("警告选择")} defaultValue="Lucy" />
</div>
空号
notFoundContent 接受空列表的文本、数字、null 或 Svelte 片段。
<script lang="ts">
import { Select } from '@woodger/antd';
</script>
{#snippet empty()}<span
role="status"
>{("没有匹配项。改变你的要求。")}</span>{/snippet}
<Select
options={([])}
showSearch
aria-label={("清空搜索选择")}
notFoundContent={(empty)}
placeholder={("开始您的搜索")}
/>
列表容器
getPopupContainer 指定弹出容器。根 Select 在挂载后传递给 getter。
<script lang="ts">
import { Select } from '@woodger/antd';
let host = $state<HTMLDivElement>();
const options = ["第一的", "第二", "第三"].map(label => ({ value: label, label }));
</script>
<style>
.host {
position: relative;
padding: 16px;
border: 1px dashed var(--ant-color-border);
border-radius: 6px;
}
</style>
<div class="host" bind:this={host}>
<Select
options={(options)}
aria-label={("选择列表容器")}
getPopupContainer={trigger => host ?? trigger}
placeholder={("在此容器内列出")}
/>
</div>
Select 面板位置
placement 设置首选位置,popupAlign 添加间距,transitionName 选择动画。空间不足时浮层可以翻转。
<script lang="ts">
import { RadioGroup, Select, type SelectProps } from '@woodger/antd';
const placements = ['topLeft', 'topRight', 'bottomLeft', 'bottomRight'];
const options = ['Button', 'Input', 'Select'].map(value => ({ value, label: value }));
let placement = $state<SelectProps['placement']>('bottomLeft');
</script>
<style>
.controls {
margin-bottom: 16px;
}
</style>
<div class="controls">
<RadioGroup
aria-label={("Select 面板位置")}
options={placements}
bind:value={placement}
/>
</div>
<Select
aria-label={("可选择面板位置的 Select")}
{options}
{placement}
popupAlign={{ offset: [0, placement?.startsWith('top') ? -8 : 8] }}
transitionName="ant-slide-up"
placeholder={("选择组件")}
/>
Select 面板宽度
true 匹配字段宽度,false 按内容自适应。数字设置像素宽度,小于字段宽度的值不会缩窄面板。
<script lang="ts">
import { RadioGroup, Select } from '@woodger/antd';
const widths = [true, false, 120, 320].map(value => ({ value, label: String(value) }));
const options = [
{ value: 'button', label: 'Button' },
{ value: 'settings', label: "组件设置与本地化" }
];
let width = $state<boolean | number>(true);
</script>
<style>
.controls { margin-bottom: 16px; }
.field {
width: 180px;
max-width: 100%;
}
</style>
<div class="controls">
<RadioGroup
aria-label={("Select 面板宽度")}
options={widths}
bind:value={width}
/>
</div>
<div class="field">
<Select
aria-label={("可设置面板宽度的 Select")}
options={(options)}
popupMatchSelectWidth={width}
style="
width: 100%;
min-width: 0;
"
placeholder={("选择组件")}
/>
</div>
入选球队: 2.
<script lang="ts">
import { Button, Form, FormItem, Select, createForm, type SelectOption } from '@woodger/antd';
const teams: SelectOption<number>[] = [
{ value: 0, label: "开发" },
{ value: 1, label: "设计" },
{ value: 2, label: "分析" },
{ value: 3, label: "支持" },
{ value: 4, label: "档案", disabled: true }
];
const form = createForm<{ teams: number[] }>({
initialValues: { teams: [0, 1] },
rules: ({
teams: [
{ required: true, message: "至少选择一支球队。" },
{ max: 3, message: "选择不超过三支球队。" }
]
})
});
let result = $state('');
function finish(values: { teams: number[] }) {
const labels = values.teams.map(value => {
const team = teams.find(team => team.value === value);
return team?.label;
});
const selectedTeams = labels.join(', ');
result = ("保存的命令: " + String((selectedTeams)) + ".");
}
</script>
<style>
.example { max-width: 640px; }
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.selection {
margin: 16px 0 0;
color: var(--ant-color-text-tertiary);
font-size: 12px;
}
.result {
margin: 16px 0 0;
color: var(--ant-color-success);
}
</style>
<div class="example">
<Form {form} onFinish={finish}>
<FormItem name="teams" label={("参赛队伍")} help={("选择一到三支球队。")}>
<Select
mode="multiple"
options={(teams)}
value={form.values.teams}
onValueChange={(value) => {
form.setFieldValue('teams', value);
result = '';
}}
allowClear
placeholder={("选择团队")}
/>
</FormItem>
<div
class="actions"
><Button
type="primary"
htmlType="submit"
loading={form.isSubmitting}
>{("保存命令")}</Button><Button
htmlType="reset"
onclick={() => { result = ''; }}
>{("复位命令")}</Button></div>
</Form>
<p class="selection" role="status" aria-label={("入选球队")}>{("入选球队: ")}{(form.values.teams.length)}.</p>
{#if result}<p class="result" role="status">{result}</p>{/if}
</div>
分隔符和输入解析
分隔符数组和整个字符串函数;本机解析会删除边缘周围的空白。
<script lang="ts">
import { Select } from '@woodger/antd';
let automatic = $state<string[]>([]);
let custom = $state<string[]>([]);
function tokenize(input: string) {
return /[,;\n]/.test(input)
? input.split(/[,;\n]/).map(value => value.trim()).filter(Boolean)
: [];
}
</script>
<style>
.example {
display: grid;
gap: 12px;
}
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<Select
mode="tags"
bind:value={automatic}
tokenSeparators={[',', ';', '\n']}
aria-label={("标签分隔符")}
placeholder={("Svelte,TypeScript")}
allowClear
/>
<output aria-label={("带分隔符的标签")}>{JSON.stringify(automatic)}</output>
<Select mode="tags" bind:value={custom} tokenSeparators={tokenize}
aria-label={("自己的标签解析")} placeholder={("边缘周围的空白被删除")} allowClear />
<output
aria-label={("自己分析后的标签")}
>{JSON.stringify(custom)}</output>
</div>
限制选择
maxCount=2 限制新值;可以取消选择所选的选项。
<script lang="ts">
import { Select } from '@woodger/antd';
const options = ["开发", "设计", "分析", "支持"]
.map((label, value) => ({ value, label }));
let values = $state<number[]>([0]);
</script>
<style>
output {
display: block;
margin-top: 12px;
overflow-wrap: anywhere;
}
</style>
<Select mode="multiple" options={(options)} bind:value={values} maxCount={2}
aria-label={("不超过两队")} allowClear />
<output aria-label={("受限命令")}>{JSON.stringify(values)}{(" · 最多2个")}</output>
标签的文本和数量
标题截断、maxTagCount 和摘要标签片段保留其完整值。
<script lang="ts">
import { Checkbox, Select, type SelectOmittedTag } from '@woodger/antd';
const options = ['Svelte', 'TypeScript', 'Accessibility', 'Internationalization']
.map(label => ({ value: label, label }));
let values = $state(options.map(option => option.value));
let all = $state(false);
</script>
<style>
.example {
display: grid;
gap: 12px;
}
output { overflow-wrap: anywhere; }
</style>
{#snippet omitted(tags: SelectOmittedTag<string>[])}
<span title={tags.map(tag => tag.label).join(', ')}>{("更多的 ")}{(tags.length)}</span>
{/snippet}
<div class="example">
<Checkbox bind:checked={all}>{("显示所有标签")}</Checkbox>
<Select
mode="multiple"
options={(options)}
bind:value={values}
maxTagCount={all ? undefined : 2}
maxTagTextLength={8}
maxTagPlaceholder={omitted}
aria-label={("选择摘要标签")}
/>
<output aria-label={("摘要标签背后的值")}>{JSON.stringify(values)}</output>
</div>
大列表
100000 个选项的虚拟滚动,通过 SelectRef 调用 scrollTo、focus 和 blur。
<script lang="ts">
import { tick } from 'svelte';
import { Button, Select, type SelectRef } from '@woodger/antd';
const options = Array.from({ length: 100000 }, (_, index) => {
const value = `${index.toString(36)}${index}`;
return { value, label: value, disabled: index === 10 };
});
let control = $state<SelectRef>();
let value = $state(['a10', 'c12']);
let opened = $state(false);
async function showLastOption() {
opened = true;
await tick();
control?.scrollTo({ index: options.length - 1, align: 'bottom' });
control?.focus();
}
</script>
<style>
.example {
display: grid;
gap: 16px;
min-width: 0;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
output {
color: var(--ant-color-text-secondary);
overflow-wrap: anywhere;
}
</style>
<div class="example">
<div>{("选项数量: ")}{options.length}</div>
<Select
{options}
mode="multiple"
virtual
bind:this={control}
bind:value
bind:open={opened}
aria-label={("Select 大列表")}
placeholder={("选择选项")}
style="width:100%"
/>
<div class="actions">
<Button onclick={showLastOption}>{("跳转到最后一个选项")}</Button>
<Button onclick={() => control?.focus()}>{("聚焦 Select")}</Button>
<Button onclick={() => control?.blur()}>{("移除 Select 焦点")}</Button>
</div>
<output aria-label={("大列表的选中值")}>
{JSON.stringify(value)}
</output>
</div>
<script lang="ts">
import { Select, Tag, type SelectTagInfo } from '@woodger/antd';
const options = ['Svelte', 'TypeScript', 'CSS'].map(label => ({ value: label, label }));
let values = $state(options.map(option => option.value));
</script>
<style>
output {
display: block;
margin-top: 12px;
overflow-wrap: anywhere;
}
</style>
{#snippet tag(info: SelectTagInfo<string>)}
<Tag color={info.isMaxTag ? undefined : 'green'} closable={info.closable}
disabled={info.disabled} onClose={info.onClose}
closeLabel={info.isMaxTag ? undefined : `删除您的标签 ${info.value}`}
style="margin-inline-end: 4px"
onmousedown={event => {
event.preventDefault();
event.stopPropagation();
}}>{@render info.label()}</Tag>
{/snippet}
<Select mode="multiple" options={(options)} bind:value={values} maxTagCount={2}
tagRender={tag} aria-label={("自定义选择标签")} />
<output aria-label={("自己的标签值")}>{JSON.stringify(values)}</output>
带有描述的项目
optionRender 获取源数据和索引;所选值的 label 仍为文本。
<script lang="ts">
import { Select, type SelectFlattenOption } from '@woodger/antd';
interface Technology {
value: string;
label: string;
description: string;
}
const options: Technology[] = [
{ value: 'svelte', label: 'Svelte', description: "反应式接口" },
{ value: 'typescript', label: 'TypeScript', description: "类型检查" },
{ value: 'css', label: 'CSS', description: "页面设计" }
];
let value = $state<string>();
</script>
<style>
.option {
display: grid;
gap: 2px;
}
.description {
font-size: 12px;
color: var(--ant-color-text-secondary);
}
output {
display: block;
margin-top: 12px;
overflow-wrap: anywhere;
}
</style>
{#snippet optionContent(
option: SelectFlattenOption<string, Technology>,
info: { index: number }
)}
<span class="option">
<strong>{(info.index + 1)}. {(option.data.label)}</strong>
<span class="description">{(option.data.description)}</span>
</span>
{/snippet}
<Select
options={(options)}
bind:value
optionRender={optionContent}
showSearch
aria-label={("带有描述的项目")}
placeholder={("选择技术")}
/>
<output aria-label={("带有描述的项目的含义")}>{(value
?? ("未选择"))}</output>
开度控制
bind:open 和 open/onOpenChange:所有者接受或拒绝请求。空输出保留数字内容 0。
<script lang="ts">
import { Button, Checkbox, Select } from '@woodger/antd';
const options = ["阿尔法", "贝塔", "伽玛"].map(label => ({ value: label, label }));
let boundOpen = $state(false);
let boundValue = $state<string>();
let boundRequests = $state<boolean[]>([]);
let ownerOpen = $state(false);
let accept = $state(true);
let ownerRequests = $state<boolean[]>([]);
function requestOpen(next: boolean) {
ownerRequests = [...ownerRequests, next];
if (accept) ownerOpen = next;
}
</script>
<style>
.example {
display: grid;
gap: 12px;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Button
onclick={() => { boundOpen = true; }}
>{("打开相关列表")}</Button>
<Button
onclick={() => { boundOpen = false; }}
>{("关闭链接列表")}</Button>
</div>
<Select options={(options)} bind:open={boundOpen} bind:value={boundValue}
onOpenChange={next => { boundRequests = [...boundRequests, next]; }}
aria-label={("相关可见性选择")} placeholder={("选择值")} />
<output aria-label={("相关空缺选择")}>
{(boundOpen ? "打开" : "关闭")}{(";要求: ")}{JSON
.stringify(boundRequests)}
</output>
<Checkbox bind:checked={accept}>{("接受列表请求")}</Checkbox>
<Select options={(options)} open={ownerOpen} onOpenChange={requestOpen} showSearch
notFoundContent={(0)} aria-label={("所有者选择可见性")} />
<output aria-label={("打开由所有者选择")}>
{(ownerOpen ? "打开" : "关闭")}{(";要求: ")}{JSON
.stringify(ownerRequests)}
</output>
</div>
DefaultOpen 在创建时生效。稍后更改它不会重新打开列表。
初次开业
defaultOpen 在挂载后应用; SSR 仍然关闭。更改初始属性不会重新打开列表。
<script lang="ts">
import { Checkbox, Select } from '@woodger/antd';
const options = ["第一的", "第二"].map(label => ({ value: label, label }));
let initialOpen = $state(true);
let disabled = $state(false);
let requests = $state<boolean[]>([]);
</script>
<style>
.example {
display: grid;
gap: 12px;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output { overflow-wrap: anywhere; }
p { margin: 0; }
</style>
<div class="example">
<Select options={(options)} defaultOpen={initialOpen} {disabled}
onOpenChange={next => { requests = [...requests, next]; }}
aria-label={("初始可见性选择")} placeholder={("挂载后打开")} />
<div class="controls">
<Checkbox bind:checked={initialOpen}>{("初次开业")}</Checkbox>
<Checkbox bind:checked={disabled}>{("禁用选择")}</Checkbox>
</div>
<output
aria-label={("初始选择查询")}
>{JSON.stringify(requests)}</output>
<p>{("DefaultOpen 在创建时生效。稍后更改它不会重新打开列表。")}</p>
</div>
控件、标签和弹出窗口遵循 prefixCls。无论本地类和主题如何,服务变量都共享一个公共名称空间。保存打开的列表、搜索输入和选择。
选择 CSS 前缀
通用命名空间ConfigProvider和本地 prefixCls;当名称更改时,组件的状态将被保留。
<script lang="ts">
import { Checkbox, ConfigProvider, Select } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-select' : '');
let value = $state<string[]>(['docs']);
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("通用前缀 选择套件")}</Checkbox>
<Checkbox bind:checked={local}>{("本地前缀选择")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'select-theme' } }}>
<div class="prefix-stage">
<Select
prefixCls={localPrefix}
mode="multiple"
bind:value
showSearch
aria-label={("选择带前缀的")}
style="width:100%"
options={([
{ value: 'docs', label: "文档" }, { value: 'examples', label: "示例" }
])}
/>
<output
aria-label={("选择带前缀的")}
>{JSON.stringify(value)}</output>
</div>
</ConfigProvider>
<output
aria-label={("选择 CSS 前缀")}
>{("一般的: ")}{prefix}{(";当地的: ")}{(localPrefix
|| ("来自提供商"))}</output>
<p>
{("控件、标签和弹出窗口遵循 prefixCls。无论本地类和主题如何,服务变量都共享一个公共名称空间。保存打开的列表、搜索输入和选择。")}
</p>
</div>
官方示例覆盖
已与 Ant Design 6.7.2 的 Select 页面核对。“在应用中”表示组合属性,“部分”表示覆盖不完整,“无 API”表示功能不可用。示例使用软件包公共 API。
| 蚂蚁设计主题 | 状态 | 解释 |
|---|---|---|
| Basic Usage | 可用的· 例子 | 单选、disabled、loading 和清除。 |
| Select with search field | 可用的· 例子 | 按 label 搜索。 |
| Custom Search | 可用的· 例子 | 谓词 filterOption。 |
| Multi field search | 可用的· 例子 | showSearch.optionFilterProp 使用 OR 搜索多个字段。 |
| multiple selection | 可用的· 例子 | 选定值的数组。 |
| Sizes | 可用的· 例子 | 来自公共 API 的三种尺寸。 |
| Custom dropdown options | 可用的· 例子 | optionRender 接收原始记录及包含分组标题的索引。 |
| Search with sort | 可用的· 例子 | showSearch.filterSort 在不更改 options 的情况下对过滤结果进行排序。 |
| Tags | 可用的· 例子 | 自由字符串值;options 是可选的。 |
| Option Group | 可用的· 例子 | 一层分组、搜索,以及跳过禁用选项的导航。 |
| coordinate | 在应用程序中· 例子 | 通过应用程序模型进行两个 Select 的通信。 |
| Get value of selected item | 可用的· 例子 | labelInValue 在模型和选择事件中保留 value 和 label。 |
| Automatic tokenization | 可用的· 例子 | multiple/tags 的 tokenSeparators 数组。 |
| Custom tokenization | 可用的· 例子 | tokenSeparators 函数接收整个输入字符串。 |
| Search and Select Users | 可用的· 例子 | 引导式搜索和应用内下载选项。 |
| Prefix and Suffix | 可用的· 例子 | prefix 在字段前添加内容;suffix 根据状态替换尾部区域。 |
| Custom dropdown | 可用的· 例子 | popupRender 通过 Svelte snippet 扩展原始菜单。 |
| Hide Already Selected | 可用的· 例子 | 从 options 移除选项后,所选标签保留原名称,onDeselect 仍收到原始记录。 |
| Variants | 可用的· 例子 | single/multiple 的 outlined、filled、borderless 和 underlined,包括从上下文继承。 |
| Custom Tag Render | 可用的· 例子 | Snippet 接收 label、键入的 value 和 onClose;摘要标签不会被删除。 |
| Custom Selected Label Render | 可用的· 例子 | 纯 labelRender 函数返回文本或 Svelte snippet。 |
| Responsive maxTagCount | 可用的· 例子 | 字段宽度决定了可见标签;隐藏的意义仍然存在于模型和形式中。 |
| Big Data | 可用的· 例子 | 100000 个选项,支持测量式虚拟滚动和 scrollTo 跳转。 |
| Status | 可用的· 例子 | error 和 warning。 |
| Placement | 可用的· 例子 | 四个物理面板角,根据可用空间调整。 |
| Max Count | 可用的· 例子 | 通过 multiple/tags 中的 maxCount 限制新值。 |
| Custom semantic dom styling | 可用的· 例子 | classNames/styles 支持对象和函数,包括 ConfigProvider.select。 |
API
以下是安装包的参数。确切的定义是公开的 SelectProps, SelectOption 和 SelectSearchConfig。 Single 存储字符串或数字,multiple 存储相同类型的数组,tags 还允许新字符串。
| 属性 | 描述 | 类型 | 默认 |
|---|---|---|---|
showAction | focus 使编辑器在获得焦点时打开列表。 | readonly ("focus" | "click")[] | — |
virtual | 启用列表窗口渲染;没有局部属性时采用 ConfigProvider.virtual。 | boolean | ConfigProvider / true |
listHeight | 内部视口的最大高度,单位 px;0 表示不限制。 | number | 256 |
listItemHeight | 测量前的行高估计;0 关闭窗口渲染。 | number | token.controlHeight |
showScrollBar | Optional 在滚动时显示滚动条,3 秒后隐藏。 | boolean | 'optional' | optional |
labelInValue | 模型和事件传递 { value, label };multiple/tags 使用对象数组。 | boolean | false |
optionLabelProp | 原始记录中用于选中标签的字段。使用方显式提供的 label 优先。 | string | fieldNames.label |
labelRender | 纯显示函数,包含 Snippet 内容。null/undefined 回退到原始 value。 | (info: SelectLabelRenderInfo) => RenderEmptyContent | undefined |
popupRender | 纯函数接收原始菜单;在 SSR 和关闭状态也运行。 | SelectPopupRender | undefined |
prefix | 编辑器前的内容。包括 0 在内的假值标量不创建元素。 | RenderEmptyContent | undefined |
rootClassName | control 和面板的共享类名;原有 class 仍用于 Select 外层容器。 | string | undefined |
classNames | control 和面板各部分的类名;局部类名与 ConfigProvider.select 合并。 | SelectClassNames | ((info: SelectSemanticInfo) => SelectClassNames) | undefined |
styles | 各部分样式。局部 popup leaf 完整替换相应的 provider leaf。 | SelectStyles | ((info: SelectSemanticInfo) => SelectStyles) | undefined |
style | CSS 对象设置控件样式;CSS 字符串保留外层容器样式。 | SelectStyle | undefined |
defaultActiveFirstOption | 打开列表或搜索变化时,激活第一个可用选项。 | boolean | true |
onActive | 报告活动选项或 null;选中值变化是独立事件。 | (value: Value | string | null) => void | — |
nativeElement | 挂载后的根 div 或已注册的 components.root 元素。 | RootElement | HTMLDivElement | undefined | undefined |
inputElement | 挂载后的原生 input 或已注册的 components.input 元素。 | EditorElement | HTMLInputElement | undefined | undefined |
components | Input 替换编辑器;root 替换整个字段且优先级更高。Snippet 转发 attributes 并通过 register 注册元素。扩展 API 尚未完整移植。 | SelectComponents<RootElement, EditorElement> | undefined |
suffix | 替换整个尾部区域,包括 Form 反馈。纯函数接收 searchValue、open、focused、showSearch 和 loading;返回 null/undefined 时恢复默认内容。 | SelectRenderNode<SelectSuffixInfo> | 标准图标 |
loadingIcon | loading=true 时默认尾部区域中的加载图标。 | RenderEmptyContent | 从上下文来看 |
menuItemSelectedIcon | 选项图标;纯函数接收 value、disabled 和 isSelected。 | SelectRenderNode<SelectMenuItemIconInfo<Value>> | 从上下文来看 |
removeIcon | 普通 multiple/tags 标签的删除图标,不替换 tagRender 中的按钮。 | SelectRenderNode<undefined> | 从上下文来看 |
onInputKeyDown | 编辑器键盘事件;preventDefault 不会自动取消选择或 tokenSeparators。 | (event: KeyboardEvent) => void | — |
prefixCls | 组件及其部件的完整 CSS 前缀。非空本地 prop 优先;空字符串和 undefined 继承ConfigProvider。主题的命名空间是单独设置的。 | string | ConfigProvider.prefixCls + "-select" |
variant | 本地 variant → 最接近的 Form.variant → ConfigProvider.select.variant → 一般 ConfigProvider.variant → outlined。 | Variant | 从上下文/概述 |
options | 原始记录和一层分组,value/label/options 字段通过 fieldNames 指定。 | readonly OptionType[] | [] |
fieldNames | 原始数据中值、标签、子项和分组标题的字段名。 | SelectFieldNames | value / label / options; groupLabel = label |
value | bind:value 绑定值或数组;labelInValue 启用对象。null 清空选择。 | SelectValueModel<Value, Mode, LabelInValue> | null | undefined |
defaultValue | 初始模型由 mode 和 labelInValue 决定;原生 reset 恢复初始模型。 | Value | SelectLabelValue<Value> | readonly (Value | SelectLabelValue<Value>)[] | null | undefined |
mode | 默认为单选;multiple 选择现成的选项,tags 创建字符串。 | multiple | tags | undefined |
showSearch | 启用搜索。该对象配置搜索字符串、回调和本地过滤。 | boolean | SelectSearchConfig<Value, OptionType> | multiple/tags: true; single: false |
allowClear | 清除结果:single → undefined,multiple/tags → []。对象设置 clearIcon 和 label;无障碍名称由应用翻译。 | boolean | SelectAllowClear | ConfigProvider.select / false |
loading | 显示指示器和 aria-busy;请求管理保留在应用程序中。 | boolean | undefined |
notFoundContent | 一般内容,包括 boolean 数组和 readonly 数组。 null/false/空字符串隐藏空 popup,0 可见; undefined 继承 renderEmpty。 | RenderEmptyContent | 从上下文来看 |
size | large、medium、small;通常的高度取决于主题。 | ComponentSize | 从上下文来看 |
status | 视力状况;error 添加了 aria-invalid。 | error | warning | 从表单项 |
disabled | 阻止选择并从提交中排除本机字段。 | boolean | 从上下文来看 |
placement | 首选面板位置。提供者的 popupOverflow 设置溢出计算区域,getPopupContainer 选择 DOM 容器。 | bottomLeft | bottomRight | topLeft | topRight | 左下角;在 RTL 右下角 |
popupAlign | 所选浮层位置的对齐点、偏移量和溢出调整。 | SelectPopupAlign | — |
builtinPlacements | placement 各取值对应的浮层位置映射。 | Readonly<Record<string, SelectPopupAlign>> | 内置映射 |
transitionName | 浮层 CSS 动画的名称。 | string | 组件动画 |
popupMatchSelectWidth | true 使用控件宽度,false 按内容确定宽度,数值指定 px 宽度。控件宽度始终为最小值;undefined 继承 ConfigProvider。false 关闭虚拟化。 | boolean | number | ConfigProvider / true |
getPopupContainer | 选择列表的 DOM 容器。没有 getter 时保留原有父节点;面板始终使用 fixed 原生 popover 显示在页面上层。 | (trigger: HTMLElement) => HTMLElement | ShadowRoot | 来自上下文,否则为组件父节点 |
onPopupScroll | 内部视口的原生滚动事件;currentTarget 和 this 指向其 div。 | HTMLAttributes<HTMLDivElement>[onscroll] | — |
onValueChange | 选择和清除后接收模型,onChange 还提供记录数据。 | (value: SelectValueModel<Value, Mode, LabelInValue> | undefined) => void | — |
onChange | 选中值变化时调用。第二个参数包含原始记录的浅拷贝,没有对应记录的自由标签使用 {}。 | SelectProps<Value, Mode, OptionType, LabelInValue>["onChange"] | — |
onSelect | 每次选择选项时调用,包括 value 不变的重复单选。 | SelectProps<Value, Mode, OptionType, LabelInValue>["onSelect"] | — |
onDeselect | multiple/tags 移除单个值时调用,全部清除不会调用。 | SelectProps<Value, Mode, OptionType, LabelInValue>["onDeselect"] | — |
onClear | 用户清除时在 onChange 之前调用,single 结果为 undefined,multiple/tags 为 []。 | () => void | — |
onOpenChange | 请求更改可见性。open 时,业主接受或拒绝请求;初始和外部更新不会触发回调。 | (open: boolean) => void | — |
open | 托管可见性,包括 bind:open。优先于 defaultOpen; SSR 仍然关闭。 | boolean | undefined |
defaultOpen | 安装后初始非托管可见性。后续的 prop 更改不会重新打开列表。 | boolean | false |
class | 标准字段外层容器的类名。 | string | — |
tokenSeparators | 分隔符数组或整个字符串的函数。multiple 接受现成的选择;标签创建字符串。 | SelectTokenSeparators | — |
maxCount | 新选定的 multiple/tags 值的最大值。已经传递的数组不会被截断。 | number | 没有限制 |
maxTagTextLength | 将可见标签文本限制为 UTF-16,保留完整 label 和 value;代理对没有被破坏。 | number | 没有限制 |
maxTagCount | 仅显示限制。responsive 测量浏览器中的宽度; SSR 显示所有值。 | number | responsive | 所有标签 |
maxTagPlaceholder | 带有隐藏 SelectOmittedTag 的标量或片段。null/undefined 选择 default; false 留下空摘要。 | SelectTagPlaceholder<Value> | + N ... |
tagRender | 常规标签和摘要标签的内容 multiple/tags。label - 片段;摘要没有 value、index 和 onClose。 | Snippet<[SelectTagInfo<Value>]> | — |
optionRender | Data 包含原始记录,label 类型为 unknown,groupOption 标记分组子项。 | Snippet<[SelectFlattenOption<Value, OptionType>, { index: number }]> | — |
showSearch
| 属性 | 描述 | 类型 | 默认 |
|---|---|---|---|
showSearch.searchIcon | 字段展开时默认尾部区域中的搜索图标。 | RenderEmptyContent | 从上下文来看 |
showSearch.searchValue | 托管搜索栏。options 和所选值独立更新。 | string | undefined |
showSearch.onSearch | 获取用户的搜索字符串;应用程序加载数据。 | (search: string) => void | — |
showSearch.filterOption | 本地过滤或谓词(搜索、option)。对于远程搜索,将其设置为 false。 | boolean | predicate | true |
showSearch.optionFilterProp | 原始 option 的字段,通过 OR 组合。 filterOption 谓词优先。 | string | readonly string[] | single/multiple: label; tags: value |
showSearch.filterSort | 对过滤列表(包括合成 tags)进行排序,同时保留所有者的 options。 | (a, b, { searchValue }) => number | — |
showSearch.autoClearSearchValue | 在 multiple/tags 中选择时清除本地搜索。托管的 searchValue 更新所有者。 | boolean | true |
single/multiple 时,搜索过滤列表;标签创建自由行。 optionFilterProp 和 filterSort 位于 showSearch 内部。对于已删除的数据,设置 showSearch.filterOption=false 并通过 showSearch.onSearch 更新 options。
上下文和原生形式
ConfigProvider.select 仅接受 variant。本地 variant 优先于最近的 Form.variant,然后应用 select.variant、全局 ConfigProvider.variant 和 outlined。尺寸和外观设置不会更改所选值。
大小和可用性继承自 ConfigProvider 和 Form。 id, name, required, aria-* 并将本机事件传递给输入。 FormData 包含字符串,model包含原始值类型。
方法
bind:this 提供 SelectRef,包含 focus、blur 和 scrollTo 方法。
bind:nativeElement 提供根元素,bind:inputElement 提供编辑器。
open 支持 bind:open 和受控的 open/onOpenChange;defaultOpen 在挂载后设置初始状态。通过 id 将控件与 HTML label 关联,并使用键盘操作。
| 方法 | 类型 | 应用 |
|---|---|---|
focus | (options?: FocusOptions) => void | 将焦点移入编辑器。 |
blur | () => void | 移除编辑器焦点。 |
scrollTo | (config?: SelectScrollConfig | null) => void | 按 index、key 或 top/left 位置滚动列表。 |
大列表 展示打开面板后跳转到最后一个选项。
Semantic DOM
classNames 和 styles 通过对象或纯函数设置 Select 和面板各部分样式。ConfigProvider.select 提供共享值;rootClassName 用于 control 和面板。 Select 各部分样式.
root / prefix / suffix / input / placeholder / content / item / itemContent /
itemRemove / clear / popup.root / popup.list / popup.listItem
注册令牌
组件代币通过以下方式传输 ConfigProvider.theme.components.Select.
<script lang="ts">
import { ConfigProvider, Select } from '@woodger/antd';
</script>
<ConfigProvider theme={{
cssVar: {},
components: {
Select: {
activeBorderColor: '#389e0d',
hoverBorderColor: '#73d13d',
optionSelectedBg: '#f6ffed',
optionSelectedColor: '#237804'
}
}
}}>
<Select aria-label={("自定义主题选择")} defaultValue="day" options={([
{ value: 'day', label: "天" },
{ value: 'week', label: "周" },
{ value: 'month', label: "月" }
])} />
</ConfigProvider>
| 代币 | 目的 |
|---|---|
activeBorderColor | 对焦框颜色。 |
activeOutlineColor | 焦点轮廓颜色。 |
clearBg | 干净的按钮背景。 |
hoverBorderColor | 悬停时的框架。 |
multipleItemBg | 所选标签的背景。 |
multipleItemBorderColor | 所选标签的框架。 |
multipleItemBorderColorDisabled | 标签框架不可用。 |
multipleItemColorDisabled | 无法访问的标签的文本。 |
multipleItemHeight | 正常标签高度。 |
multipleItemHeightLG | 大标签的高度。 |
multipleItemHeightSM | 小标签的高度。 |
multipleSelectorBgDisabled | 后台无法访问 multiple。 |
optionActiveBg | 活动变体的背景。 |
optionFontSize | 选项文字大小。 |
optionHeight | 高度选项。 |
optionLineHeight | 选项的行高。 |
optionPadding | 选项缩进。 |
optionSelectedBg | 所选选项的背景。 |
optionSelectedColor | 所选选项的文本。 |
optionSelectedFontWeight | 所选选项的文本粗细。 |
selectorBg | 领域背景。 |
showArrowPaddingInlineEnd | 放置箭头的地方。 |
singleItemHeightLG | 大单个值的高度。 |
zIndexPopup | 列表层。 |
当前主题的常用标记
数值被读取 theme.useToken() 并随标题中的设置一起更改。
| 代币 | 目的 | 当前值 |
|---|---|---|
colorBgContainer | 常规字段的背景。 | #ffffff |
colorBgContainerDisabled | 无法访问的图标的背景。 | rgba(0,0,0,0.04) |
colorBgElevated | 下拉背景。 | #ffffff |
colorBorder | 镜框颜色。 | #d9d9d9 |
colorBorderDisabled | 不可访问元素的框架。 | #d9d9d9 |
colorError | 错误的主要颜色。 | #ff4d4f |
colorErrorAffix | 附加颜色错误。 | #ff4d4f |
colorErrorBg | 错误背景。 | #fff2f0 |
colorErrorBgHover | 悬停错误背景。 | #fff1f0 |
colorErrorBorderHover | 悬停错误框。 | #ffa39e |
colorErrorOutline | 错误大纲。 | rgba(255,38,5,0.06) |
colorErrorText | 错误文本。 | #ff4d4f |
colorFillQuaternary | 填充力弱。 | rgba(0,0,0,0.02) |
colorFillSecondary | 二次填充。 | rgba(0,0,0,0.06) |
colorFillTertiary | 三次充填。 | rgba(0,0,0,0.04) |
colorIcon | 图标颜色。 | rgba(0,0,0,0.45) |
colorIconHover | 图标悬停颜色。 | rgba(0,0,0,0.88) |
colorPrimary | 交互状态的主要颜色。 | #2f54eb |
colorPrimaryBorder | 主色的浅色轮廓。 | #adc6ff |
colorSplit | 分隔符颜色。 | rgba(5,5,5,0.06) |
colorText | 标志色。 | rgba(0,0,0,0.88) |
colorTextDescription | 描述颜色。 | rgba(0,0,0,0.45) |
colorTextDisabled | 不可用签名的颜色。 | rgba(0,0,0,0.25) |
colorTextPlaceholder | 输入提示颜色。 | rgba(0,0,0,0.25) |
colorTextQuaternary | 背景文字颜色。 | rgba(0,0,0,0.25) |
colorWarning | 主要警告颜色。 | #faad14 |
colorWarningAffix | 添加颜色警告。 | #faad14 |
colorWarningBg | 警告背景。 | #fffbe6 |
colorWarningBgHover | 悬停警报背景。 | #fff1b8 |
colorWarningHover | 悬停警报颜色。 | #ffd666 |
colorWarningOutline | 报警电路。 | rgba(255,215,5,0.1) |
borderRadius | 正常舍入。 | 6 |
borderRadiusLG | 大舍入。 | 8 |
borderRadiusSM | 图标四舍五入。 | 4 |
borderRadiusXS | 最小舍入。 | 2 |
boxShadowSecondary | 下拉阴影。 |
0 6px 16px 0 rgba(0,0,0,0.08),
0 3px 6px -4px rgba(0,0,0,0.12),
0 9px 28px 8px rgba(0,0,0,0.05)
|
controlHeight | 正常场的高度。 | 32 |
controlHeightLG | 大田地的高度。 | 40 |
controlHeightSM | 小田地的高度。 | 24 |
controlItemBgActiveHover | 悬停时所选项目的背景。 | #d6e4ff |
controlOutlineWidth | 元素轮廓的厚度。 | 2 |
controlPaddingHorizontal | 元素的水平内边距。 | 12 |
fontFamily | 字体家族。 | -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
'Noto Color Emoji' |
fontSize | 基本文字大小。 | 14 |
fontSizeIcon | 图标大小。 | 12 |
fontSizeLG | 大文字尺寸。 | 16 |
fontSizeSM | 文字尺寸小。 | 12 |
lineHeight | 签名行的高度。 | 1.5714285714285714 |
lineHeightLG | 行高大。 | 1.5 |
lineType | 框架线类型。 | solid |
lineWidth | 框架厚度。 | 1 |
marginXS | 外部裕度小。 | 8 |
motionDurationMid | 主要过渡的持续时间。 | 0.2s |
motionDurationSlow | 缓慢过渡的持续时间。 | 0.3s |
motionEaseInOut | 平滑的过渡曲线。 | cubic-bezier(0.645, 0.045, 0.355, 1) |
motionEaseInOutCirc | 过渡曲线。 | cubic-bezier(0.78, 0.14, 0.15, 0.86) |
motionEaseInQuint | 转变加速度曲线。 | cubic-bezier(0.755, 0.05, 0.855, 0.06) |
motionEaseOutCirc | 过渡减速曲线。 | cubic-bezier(0.08, 0.82, 0.17, 1) |
motionEaseOutQuint | 过渡减速曲线。 | cubic-bezier(0.23, 1, 0.32, 1) |
paddingSM | 小内部填充。 | 12 |
paddingXS | 图标签名的缩进。 | 8 |
paddingXXS | 最小填充。 | 4 |
FAQ
为什么输入文本不会更改所选值?
single 项/multiple 项中,搜索过滤选项;确认更改 value。对于一组自由字符串,请选择 mode="tags",对于任意文本 - 自动完成。 键盘搜索 显示带有箭头和 Enter 的选择。
为什么清理结果是 undefined 或[]?
这些是单字段格式和多字段格式。值 0 仍然是有效的选择。 数值示例 允许您检查签名、原始类型和清理。
如何获取所选选项的签名?
值与标签展示 labelInValue:模型包含 value 和 label,数字值保持其类型。使用远程数据时,即使当前结果页变化,也应保留应用所需的记录。
为什么删除的结果不显示?
检查showSearch.filterOption=false、当前搜索字符串以及options 中的数据。旧的响应不应替换新请求的结果。撤消、错误和重做处理可以在 独立的例子 中进行探索。
为什么从选项中删除 options 后签名仍然存在?
options 变化时,Select 保留已选值的标签。要在应用中取消选择,请更新 value。
下拉列表在哪里?
没有 getter 时,DOM 父节点仍在组件内部,但列表以 fixed 原生 popover 显示在页面上层。本地 getPopupContainer 或 ConfigProvider.getPopupContainer 将 DOM 移到其他容器。容器示例展示这种组合。open 控制可见性,placement 选择首选角。
Select 适合非常大的列表吗?
Select 使用虚拟滚动。可访问 listbox 包含活动选项及相邻项,可见窗口则包含测量后的行。需要为辅助技术提供完整选项 DOM 时,可以设置 virtual=false。大列表展示了 100000 个选项的使用。