Select选择器
Select 用于从列表中选择一个或多个值。它渲染一个带有 role="combobox" 的焦点元素(<div>,可搜索时为 <input>),以及放置在页面末尾的面板中的列表,因此不会被容器裁剪。SelectOption 与 SelectOptGroup 是 options 的标记写法。
何时使用
- 当列表过长、不适合用单选按钮或复选框时,使用 Select 选择一个或多个值。
- 列表较长时开启
showSearch;允许用户添加自己的值时使用mode="tags"。 - 只有两三个选项时,一组单选按钮或复选框更便于一眼看清。
代码演示
Pick a city
<script lang="ts">
import { Select } from 'svelte-ant-design';
import type { SelectValue } from 'svelte-ant-design';
let city = $state<SelectValue | undefined>();
let last = $state('no change yet');
// A string or a number is both the value and the label; an object gives them apart.
const cities = [
'Bishkek',
'Almaty',
{ value: 'tashkent', label: 'Tashkent' },
{ value: 'ulaanbaatar', label: 'Ulaanbaatar', disabled: true }
];
</script>
<!-- bind:value keeps a variable in sync with the field; onchange receives the value and the option object. -->
<Select
bind:value={city}
aria-label="City"
placeholder="Pick a city"
options={cities}
style="width: 240px"
onchange={(value, option) => (last = `onchange(${JSON.stringify(value)}, ${JSON.stringify(option)})`)}
/>
<span>The city is {city === undefined ? 'not chosen' : city}</span>
<span role="status">{last}</span>
Search a person
Label starts with ...
Type cat, dog, bird or fish
<script lang="ts">
import { Select } from 'svelte-ant-design';
import type { SelectValue } from 'svelte-ant-design';
const people = [
{ value: 'ada', label: 'Ada Lovelace', team: 'analytics' },
{ value: 'grace', label: 'Grace Hopper', team: 'compilers' },
{ value: 'linus', label: 'Linus Torvalds', team: 'kernel' },
{ value: 'margaret', label: 'Margaret Hamilton', team: 'flight software' },
{ value: 'dennis', label: 'Dennis Ritchie', team: 'compilers' }
];
let person = $state<SelectValue | undefined>();
let text = $state('');
let heard = $state('');
// Server-side search: the list is the answer of a (here, pretend) server, so the field does not filter it itself.
let found = $state<{ value: string; label: string }[]>([]);
let busy = $state(false);
let remote = $state<SelectValue | undefined>();
let timer: ReturnType<typeof setTimeout> | undefined;
function search(query: string): void {
clearTimeout(timer);
if (query === '') {
found = [];
busy = false;
return;
}
busy = true;
timer = setTimeout(() => {
found = ['cats', 'dogs', 'birds', 'fish'].filter((word) => word.includes(query.toLowerCase())).map((word) => ({ value: word, label: `${word} (${query})` }));
busy = false;
}, 400);
}
</script>
<!-- showSearch filters by label; optionFilterProp names more fields; filterSort orders the matches. -->
<Select
bind:value={person}
bind:searchValue={text}
aria-label="Person"
placeholder="Search a person"
showSearch
options={people}
optionFilterProp={['label', 'team']}
filterSort={(a, b) => String(a.label).localeCompare(String(b.label))}
notFoundContent="Nobody found"
resultsText={(count) => `${count} found`}
onsearch={(value) => (heard = `onsearch("${value}")`)}
style="width: 280px"
/>
<span>search text: "{text}"</span>
<span role="status">{heard}</span>
<!-- A function decides per option: here the text must start the label. -->
<Select
aria-label="Starts with"
placeholder="Label starts with ..."
showSearch
options={people}
filterOption={(input, option) => String(option.label).toLowerCase().startsWith(input.toLowerCase())}
style="width: 280px"
/>
<!-- filterOption={false} leaves the list to you; loading shows that it is on the way. -->
<!-- autocomplete defaults to "new-password", so browsers do not offer saved values in the search box. -->
<Select
bind:value={remote}
aria-label="Remote search"
placeholder="Type cat, dog, bird or fish"
showSearch
filterOption={false}
loading={busy}
options={found}
onsearch={search}
autocomplete="off"
style="width: 280px"
/>
Svelte TypeScript Svelte, TypeScript
Rust Rust
Svelte Rust + more Svelte, Rust, Go, Python, Kotlin
Type, then pick several
<script lang="ts">
import { Select } from 'svelte-ant-design';
import type { SelectValue } from 'svelte-ant-design';
const languages = ['Svelte', 'TypeScript', 'JavaScript', 'Rust', 'Go', 'Python', 'Kotlin', 'Margaret Hamilton\'s Apollo assembly'];
let chosen = $state<SelectValue[]>(['Svelte', 'TypeScript']);
let removed = $state('nothing removed yet');
let limited = $state<SelectValue[]>(['Rust']);
let kept = $state<SelectValue[]>(['Svelte', 'Rust', 'Go', 'Python', 'Kotlin']);
let typed = $state<SelectValue[]>([]);
</script>
<!-- The value is an array; each value is a tag with a remove button. ondeselect runs when one is removed. -->
<Select
bind:value={chosen}
aria-label="Languages"
mode="multiple"
placeholder="Pick languages"
options={languages}
allowClear
ondeselect={(value) => (removed = `removed ${value}`)}
style="width: 320px"
/>
<span>{JSON.stringify(chosen)}</span>
<span role="status">{removed}</span>
<!-- maxCount: with two values the other options are disabled. -->
<Select
bind:value={limited}
aria-label="At most two"
mode="multiple"
maxCount={2}
options={languages}
style="width: 320px"
/>
<!-- maxTagCount folds the rest into one tag; maxTagTextLength cuts a long tag. -->
<Select
bind:value={kept}
aria-label="Folded tags"
mode="multiple"
maxTagCount={2}
maxTagPlaceholder="+ more"
maxTagTextLength={8}
options={languages}
style="width: 320px"
/>
<!-- autoClearSearchValue={false}: the text stays after a selection, so several matches can be picked in a row. -->
<Select
bind:value={typed}
aria-label="Keep the search text"
mode="multiple"
autoClearSearchValue={false}
placeholder="Type, then pick several"
options={languages}
style="width: 320px"
/>
svelte svelte
Type or paste: red, green, blue
<script lang="ts">
import { Select } from 'svelte-ant-design';
import type { SelectValue } from 'svelte-ant-design';
let tags = $state<SelectValue[]>(['svelte']);
let pasted = $state<SelectValue[]>([]);
</script>
<!-- mode="tags": Enter adds the typed text as a value, even when it is not in the list. -->
<Select
bind:value={tags}
aria-label="Tags"
mode="tags"
placeholder="Type a tag and press Enter"
options={['svelte', 'typescript', 'a11y']}
style="width: 320px"
/>
<span>{JSON.stringify(tags)}</span>
<!-- tokenSeparators: a comma ends a token; a pasted "red, green, blue" becomes three values. -->
<Select
bind:value={pasted}
aria-label="Comma separated tags"
mode="tags"
tokenSeparators={[',']}
placeholder="Type or paste: red, green, blue"
style="width: 320px"
/>
<span>{JSON.stringify(pasted)}</span>
Apple
Apple
Apple
Apple
Apple
outlined
filled
borderless
underlined
error
warning
Apple
prefix
suffix
no suffix
loading
loadingIcon
Banana
Apple Cherry Apple, Cherry
<script lang="ts">
import { Select } from 'svelte-ant-design';
const fruit = ['Apple', 'Banana', 'Cherry'];
let cleared = $state<string | number | undefined>('Banana');
</script>
{#snippet star()}<span aria-hidden="true">★</span>{/snippet}
{#snippet wait()}<span aria-hidden="true">…</span>{/snippet}
{#snippet mark()}<span aria-hidden="true">✔</span>{/snippet}
{#snippet minus()}<span aria-hidden="true">−</span>{/snippet}
<!-- large is 40px high, medium 32px, small 24px; middle and default are aliases of medium. -->
<Select aria-label="Large" size="large" options={fruit} value="Apple" style="width: 160px" />
<Select aria-label="Medium" size="medium" options={fruit} value="Apple" style="width: 160px" />
<Select aria-label="Middle, an alias of medium" size="middle" options={fruit} value="Apple" style="width: 160px" />
<Select aria-label="Default, an alias of medium" size="default" options={fruit} value="Apple" style="width: 160px" />
<Select aria-label="Small" size="small" options={fruit} value="Apple" style="width: 160px" />
<!-- Four variants, two statuses. -->
<Select aria-label="Outlined" variant="outlined" options={fruit} placeholder="outlined" style="width: 160px" />
<Select aria-label="Filled" variant="filled" options={fruit} placeholder="filled" style="width: 160px" />
<Select aria-label="Borderless" variant="borderless" options={fruit} placeholder="borderless" style="width: 160px" />
<Select aria-label="Underlined" variant="underlined" options={fruit} placeholder="underlined" style="width: 160px" />
<Select aria-label="Error" status="error" options={fruit} placeholder="error" style="width: 160px" />
<Select aria-label="Warning" status="warning" options={fruit} placeholder="warning" style="width: 160px" />
<Select aria-label="Disabled" disabled options={fruit} value="Apple" style="width: 160px" />
<!-- prefix, a custom suffix (null hides it), custom icons, and loading, which takes the place of the arrow. -->
<Select aria-label="With a prefix" prefix={star} options={fruit} placeholder="prefix" style="width: 160px" />
<Select aria-label="Custom suffix" suffix="▾" options={fruit} placeholder="suffix" style="width: 160px" />
<Select aria-label="No suffix" suffix={null} options={fruit} placeholder="no suffix" style="width: 160px" />
<Select aria-label="Loading" loading options={fruit} placeholder="loading" style="width: 160px" />
<Select aria-label="Loading with an icon of your own" loading loadingIcon={wait} options={fruit} placeholder="loadingIcon" style="width: 160px" />
<Select
bind:value={cleared}
aria-label="Clearable"
allowClear={{ label: 'Forget the fruit', clearIcon: minus }}
menuItemSelectedIcon={mark}
options={fruit}
style="width: 200px"
/>
<Select
aria-label="Tags with a custom remove icon"
mode="multiple"
removeIcon="×"
options={fruit}
value={['Apple', 'Cherry']}
style="width: 240px"
/>
Pick a person
Kyrgyzstan
<script lang="ts">
import { Select } from 'svelte-ant-design';
import type { SelectValue } from 'svelte-ant-design';
// An entry with an options array is a group. A disabled option is shown and cannot be chosen.
const people = [
{
label: 'Engineers',
options: [
{ value: 'ada', label: 'Ada' },
{ value: 'linus', label: 'Linus' }
]
},
{
label: 'Scientists',
options: [
{ value: 'grace', label: 'Grace' },
{ value: 'barbara', label: 'Barbara', disabled: true }
]
}
];
// fieldNames maps the keys of your own data: here { id, name } instead of { value, label }.
const countries = [
{ name: 'Asia', members: [{ id: 'kg', name: 'Kyrgyzstan' }, { id: 'kz', name: 'Kazakhstan' }] },
{ name: 'Europe', members: [{ id: 'fr', name: 'France' }] }
];
let person = $state<SelectValue | undefined>();
let country = $state<SelectValue | undefined>('kg');
</script>
<Select bind:value={person} aria-label="Person" placeholder="Pick a person" showSearch options={people} style="width: 240px" />
<span>{JSON.stringify(person)}</span>
<Select
bind:value={country}
aria-label="Country"
options={countries}
fieldNames={{ label: 'name', value: 'id', options: 'members' }}
style="width: 240px"
/>
<span>{JSON.stringify(country)}</span>
🧮 Ada Lovelace
Linus Torvalds Linus Torvalds
<script lang="ts">
import type { Snippet } from 'svelte';
import { Button, Select } from 'svelte-ant-design';
import type { SelectOptionItem, SelectTag, SelectValue } from 'svelte-ant-design';
const people = [
{ value: 'ada', label: 'Ada Lovelace', role: 'mathematician', emoji: '🧮' },
{ value: 'grace', label: 'Grace Hopper', role: 'rear admiral', emoji: '⚓' },
{ value: 'linus', label: 'Linus Torvalds', role: 'kernel maintainer', emoji: '🐧' }
];
let one = $state<SelectValue | undefined>('ada');
let tagged = $state<SelectValue[]>(['linus']);
let wrapped = $state<SelectValue | undefined>();
let presses = $state(0);
</script>
<!-- optionRender draws an option in the list (the field keeps the plain label); labelRender draws the selected value. -->
{#snippet row(option: SelectOptionItem, index: number)}
<span>{option.emoji} <strong>{option.label}</strong> <small>{option.role} (#{index + 1})</small></span>
{/snippet}
{#snippet chosen(option: SelectOptionItem)}<span>{option.emoji} {option.label}</span>{/snippet}
<Select
bind:value={one}
aria-label="Person"
options={people}
optionRender={row}
labelRender={chosen}
popupMatchSelectWidth={320}
style="width: 240px"
/>
<!-- tagRender draws a tag; onclose removes the value, closable says whether it may be removed. -->
{#snippet tag({ value, label, closable, onclose }: SelectTag)}
<span class="chip" data-value={value}>
{label}
{#if closable}<button type="button" aria-label="Remove {value}" onclick={onclose}>×</button>{/if}
</span>
{/snippet}
<Select bind:value={tagged} aria-label="Custom tags" mode="multiple" options={people} tagRender={tag} style="width: 320px" />
<!-- popupRender wraps the list; a press on the button does not take focus from the field or close the list. -->
{#snippet panel(list: Snippet)}
<div>
{@render list()}
<div class="panel-foot">
<Button size="small" onclick={() => presses++}>Add a person ({presses})</Button>
</div>
</div>
{/snippet}
<Select bind:value={wrapped} aria-label="With a footer" options={people} popupRender={panel} style="width: 240px" />
<style>
.chip {
display: inline-flex;
gap: 4px;
align-items: center;
padding: 0 6px;
border: 1px solid var(--ads-color-border);
border-radius: 4px;
}
.chip button {
padding: 0;
border: 0;
background: none;
color: inherit;
cursor: pointer;
}
.panel-foot {
padding: 4px;
border-top: 1px solid var(--ads-color-border-secondary);
}
</style>
bottomLeft
Open me
360px list
false
listHeight 120
Controlled
container
<script lang="ts">
import { Button, Select } from 'svelte-ant-design';
import type { SelectPlacement, SelectValue } from 'svelte-ant-design';
const moods = [
{ value: 'happy', label: 'Happy' },
{ value: 'sad', label: 'Sad' },
{ value: 'long', label: 'A rather long label that needs a wider list than the field' }
];
const many = Array.from({ length: 40 }, (_, index) => ({ value: index, label: `Option ${index + 1}` }));
let placement = $state<SelectValue | undefined>('bottomLeft');
let open = $state(false);
let log = $state('nothing yet');
let scrolled = $state(0);
let host = $state<HTMLElement>();
</script>
<!-- placement: the preferred side; the list flips at the edge of the screen. -->
<Select
aria-label="Choose the placement"
bind:value={placement}
options={['bottomLeft', 'bottomRight', 'topLeft', 'topRight']}
style="width: 200px"
/>
<Select aria-label="Placement" placement={placement as SelectPlacement} options={moods} placeholder="Open me" style="width: 200px" />
<!-- popupMatchSelectWidth: a number is a width in px (never narrower than the field), false fits the content. -->
<Select aria-label="A wider list" popupMatchSelectWidth={360} options={moods} placeholder="360px list" style="width: 160px" />
<Select aria-label="A list as wide as its content" popupMatchSelectWidth={false} options={moods} placeholder="false" style="width: 160px" />
<!-- listHeight: the list is at most this high and scrolls. onpopupscroll reports it. -->
<Select
aria-label="A short list"
listHeight={120}
options={many}
placeholder="listHeight 120"
onpopupscroll={() => (scrolled += 1)}
style="width: 200px"
/>
<span>scroll events: {scrolled}</span>
<!-- bind:open controls the list; onopenchange reports the changes the user makes. -->
<Select
bind:open
aria-label="Controlled list"
options={moods}
placeholder="Controlled"
onopenchange={(value) => (log = `onopenchange(${value})`)}
style="width: 200px"
/>
<Button onclick={() => (open = !open)}>{open ? 'Close' : 'Open'} from the page</Button>
<span role="status">{log}</span>
<!-- container: where the panel is put. Here, into a box of the page instead of the end of the body. -->
<Select aria-label="In a box" container={() => host!} options={moods} placeholder="container" style="width: 200px" />
<div bind:this={host} class="host"></div>
<style>
.host {
position: relative;
min-height: 8px;
}
</style>
Free
Choose, clear, tab away
<script lang="ts">
import { Checkbox, Select } from 'svelte-ant-design';
import type { SelectValue } from 'svelte-ant-design';
const plans = [
{ value: 'free', label: 'Free' },
{ value: 'pro', label: 'Pro' },
{ value: 'team', label: 'Team' }
];
let plan = $state<SelectValue | undefined>('free');
let locked = $state(true);
let log = $state<string[]>([]);
let quiet = $state<SelectValue | undefined>();
const note = (text: string) => (log = [...log.slice(-3), text]);
</script>
<!-- A function binding decides what the field may change to: while "locked" is on, every change is refused. -->
<Select
bind:value={
() => plan,
(next) => {
if (!locked) plan = next;
}
}
aria-label="Plan"
options={plans}
style="width: 200px"
/>
<Checkbox bind:checked={locked}>The plan is locked</Checkbox>
<span>{JSON.stringify(plan)}</span>
<!-- The callbacks report what the user does, in this order: onselect, then onchange; onclear after a clear. -->
<!-- onkeydown and oninput are the native handlers of the focused element; oninputkeydown is the same key, as a callback of the Select. -->
<Select
bind:value={quiet}
aria-label="Plan, with callbacks"
allowClear
showSearch
options={plans}
placeholder="Choose, clear, tab away"
onselect={(value) => note(`onselect(${value})`)}
onchange={(value) => note(`onchange(${JSON.stringify(value)})`)}
onclear={() => note('onclear()')}
onfocus={() => note('onfocus')}
onblur={() => note('onblur')}
onkeydown={() => note('onkeydown')}
oninput={() => note('oninput')}
oninputkeydown={(event) => note(`oninputkeydown(${event.key})`)}
defaultActiveFirstOption={false}
style="width: 240px"
/>
<ol class="log" aria-label="Callbacks">
{#each log as entry, index (index)}<li>{entry}</li>{/each}
</ol>
<style>
.log {
margin: 0;
padding-inline-start: 20px;
font-family: monospace;
font-size: 12px;
}
</style>
label for
aria-label
aria-labelledby
Banana Banana
<script lang="ts">
import { Select } from 'svelte-ant-design';
const fruit = ['Apple', 'Banana', 'Cherry'];
</script>
<!-- A Select has no label of its own: name it with an external label, aria-label or aria-labelledby. -->
<!-- The label also names a field that does not search, which a native label could not do for a <div>. -->
<label for="select-labels-fruit">Fruit</label>
<Select id="select-labels-fruit" options={fruit} placeholder="label for" style="width: 200px" />
<Select aria-label="Favourite fruit" options={fruit} placeholder="aria-label" style="width: 200px" />
<span id="select-labels-colour">Colour</span>
<Select
aria-labelledby="select-labels-colour"
aria-describedby="select-labels-colour-hint"
options={['Red', 'Green']}
placeholder="aria-labelledby"
style="width: 200px"
/>
<small id="select-labels-colour-hint">The colour of the fruit</small>
<!-- The search input is a native input, so a label names it natively. aria-describedby adds the selected text after your ids. -->
<label for="select-labels-search">Search a fruit</label>
<Select id="select-labels-search" showSearch options={fruit} value="Banana" style="width: 200px" />
🍎
Apple Apple
<script lang="ts">
import { Select } from 'svelte-ant-design';
</script>
<!-- classNames adds a class to a part, styles adds inline styles to it; numbers are written as they are. -->
<!-- popup, list and listItem are in the panel; item is a selected value or a tag. -->
<Select
aria-label="Styled parts"
mode="multiple"
allowClear
prefix="🍎"
placeholder="Pick fruit"
options={['Apple', 'Banana', 'Cherry']}
value={['Apple']}
class="semantic-select"
style="width: 320px"
classNames={{ root: 'semantic-root', item: 'semantic-item', popup: 'semantic-popup', listItem: 'semantic-option' }}
styles={{
root: { 'border-style': 'dashed' },
prefix: { 'margin-inline-end': '8px' },
content: { 'padding-block': '1px' },
placeholder: { 'font-style': 'italic' },
item: { 'font-weight': 600 },
clear: { color: 'crimson' },
input: { 'letter-spacing': '0.5px' },
suffix: { opacity: 0.6 },
popup: { 'border-radius': '12px' },
list: { 'padding-block': '2px' },
listItem: { 'font-variant': 'small-caps' }
}}
/>
<style>
:global(.semantic-popup) {
outline: 1px dashed var(--ads-color-border);
}
:global(.semantic-item) {
letter-spacing: 0.2px;
}
</style>
Option B
<script lang="ts">
import { Button, Select, SelectOption, SelectOptGroup } from 'svelte-ant-design';
import type { SelectValue } from 'svelte-ant-design';
let value = $state<SelectValue | undefined>('b');
let extra = $state(false);
let keys = $state(['b', 'c', 'd']);
let ignored = $state<SelectValue | undefined>();
</script>
{#snippet bold()}<b>Rich</b> content{/snippet}
<!-- SelectOption and SelectOptGroup written inside Select give the options, in the order of the markup. -->
<Select bind:value aria-label="Options as markup" style="width: 240px">
<SelectOption value="a" label="Option A" />
{#if extra}<SelectOption value="m" label="Inserted in the middle" />{/if}
<SelectOptGroup label="A group" title="About the group" class="markup-group">
{#each keys as key (key)}
<SelectOption value={key} label={`Option ${key.toUpperCase()}`} />
{/each}
</SelectOptGroup>
<SelectOption value="rich" label="Rich option" title="Searched by its label" class="markup-option">{@render bold()}</SelectOption>
<SelectOption value="off" label="Not available" disabled />
</Select>
<span>{JSON.stringify(value)}</span>
<Button onclick={() => (extra = !extra)}>{extra ? 'Remove' : 'Insert'} an option</Button>
<Button onclick={() => (keys = [...keys].reverse())}>Reverse the group</Button>
<!-- A non-empty options prop wins: the children are ignored. -->
<Select bind:value={ignored} aria-label="Options win" options={['from options']} style="width: 240px">
<SelectOption value="ignored" label="Ignored" />
</Select>
<style>
:global(.markup-option) {
font-style: italic;
}
:global(.markup-group) {
border-top: 1px dashed var(--ads-color-border);
}
</style>
maxTagCount="responsive" (drag the corner to change the width)
Ada Lovelace Grace Hopper Linus Torvalds Margaret Hamilton Dennis Ritchie + 1 ... Ada Lovelace, Grace Hopper, Linus Torvalds, Margaret Hamilton, Dennis Ritchie
maxTagPlaceholder
Ada Lovelace Grace Hopper Linus Torvalds Margaret Hamilton Dennis Ritchie Barbara Liskov 1 more Ada Lovelace, Grace Hopper, Linus Torvalds, Margaret Hamilton, Dennis Ritchie, Barbara Liskov
<script lang="ts">
import { Select } from 'svelte-ant-design';
import type { SelectValue } from 'svelte-ant-design';
const people = ['Ada Lovelace', 'Grace Hopper', 'Linus Torvalds', 'Margaret Hamilton', 'Dennis Ritchie', 'Barbara Liskov', 'Ken Thompson', 'Radia Perlman'];
let team = $state<SelectValue[]>(people.slice(0, 5));
let reviewers = $state<SelectValue[]>(people.slice(0, 6));
</script>
<div class="stack">
<div class="field">
<span class="caption">maxTagCount="responsive" (drag the corner to change the width)</span>
<!-- One row: as many tags as fit, the rest in the last tag; typed text takes room from the tags. -->
<div class="resizable">
<Select bind:value={team} aria-label="Team" mode="multiple" maxTagCount="responsive" options={people} placeholder="Pick people" allowClear />
</div>
</div>
<div class="field">
<span class="caption">maxTagPlaceholder</span>
<!-- The snippet gets the hidden options. -->
<Select bind:value={reviewers} aria-label="Reviewers" mode="multiple" maxTagCount="responsive" options={people} style="width: 320px; max-width: 100%">
{#snippet maxTagPlaceholder(hidden)}
<span title={hidden.map((option) => option.label).join(', ')}>{hidden.length} more</span>
{/snippet}
</Select>
</div>
</div>
<style>
.stack {
display: grid;
gap: 16px;
width: 100%;
}
.field {
display: grid;
/* The column is as wide as the demo, not as the fields in it ask: on a phone they shrink with it. */
grid-template-columns: minmax(0, 1fr);
justify-items: start;
gap: 6px;
min-width: 0;
}
.caption {
color: var(--ads-color-text-secondary);
font-size: 12px;
}
/* The padding leaves room for the shadow of the focused field inside the box that clips. */
.resizable {
box-sizing: border-box;
width: 380px;
min-width: 140px;
max-width: calc(100% + 4px);
margin-inline-start: -4px;
padding: 4px 16px 4px 4px;
overflow: hidden;
resize: horizontal;
}
</style>
API
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| value | 已选值:单个值,或在 multiple 与 tags 中为数组。使用 bind:value;普通值为初始值。函数绑定可以拒绝某次更改。undefined 与 null 表示未选择;没有对应选项的值会以其自身文本显示。 | SelectValue | SelectValue[] | null | — |
| mode | multiple 与 tags 使用数组;在 tags 中,输入的文本可以成为值。default(Angular 中的名称)即单选模式。 | 'multiple' | 'tags' | 'default' | 'default' |
| options | 选项。字符串或数字既是值也是标签;带有 options 数组的项是分组。值必须唯一。最后一种类型用于 fieldNames:键名不是 label 与 value 的对象。 | ReadonlyArray<SelectValue | SelectOptionItem | SelectOptionGroup | Record<string, unknown>> | [] |
| fieldNames | 映射 options 中对象的键名。未设置 groupLabel 时,它跟随映射后的 label 键。 | { label?: string; value?: string; options?: string; groupLabel?: string } | — |
| placeholder | 未选择时显示。它不是标签:字段仍需要可访问名称。 | string | Snippet | — |
| disabled | 不可聚焦,不会展开;清除按钮与图标使用禁用颜色。 | boolean | false |
| loading | 加载图标取代箭头(或自定义 suffix);宽度不变。设置 aria-busy。列表仍可使用。 | boolean | false |
| size | 字段尺寸:高 40px、32px 或 24px。middle 与 default 为 medium 的兼容别名。在 SpaceCompact 中,未指定 size 的控件采用区块尺寸。 | 'large' | 'medium' | 'middle' | 'small' | 'default' | 'medium' |
| variant | 视觉形态。无边框形态聚焦时会绘制轮廓。 | 'outlined' | 'filled' | 'borderless' | 'underlined' | 'outlined' |
| status | 校验外观。error 还会设置 aria-invalid="true";warning 仅改变外观。 | 'error' | 'warning' | — |
| prefix | 位于已选内容之前、边框内的内容:文本或 snippet。 | string | Snippet | — |
| suffix | 替换默认的箭头;null 将其隐藏。点击它与点击字段其余部分一样会打开列表。 | string | Snippet | null | — |
| allowClear | 有选中内容时显示原生清除按钮(禁用时不显示)。点击后焦点留在字段内,依次调用 onchange 与 onclear。对象形式可设置图标、可访问名称(默认 Clear)与 tabindex。 | boolean | { clearIcon?: string | Snippet; label?: string; tabIndex?: number } | false |
| removeIcon | 替换标签上的叉号。 | string | Snippet | — |
| menuItemSelectedIcon | 列表中已选选项上的标记。默认仅在 multiple 与 tags 中显示对勾;设置此属性后单选也会显示。 | string | Snippet | — |
| loadingIcon | 替换 loading 时显示的加载图标。 | string | Snippet | — |
| showSearch | 使获得焦点的元素成为可过滤列表的文本框。默认:单选关闭,multiple 与 tags 开启。 | boolean | — |
| searchValue | 当前搜索文本。使用 bind:searchValue。列表关闭时会被清空。 | string | '' |
| onsearch | 搜索文本每次变化时调用:编辑、分隔符,以及组件自行清空文本时(关闭、失焦、autoClearSearchValue 选择后)。 | (value: string) => void | — |
| filterOption | true 按 optionFilterProp 过滤;函数逐项判断;false 保持列表原样(服务端搜索)。 | boolean | ((input: string, option: SelectOptionItem) => boolean) | true |
| filterSort | 为过滤后的选项排序。第三个参数携带搜索文本。 | (a: SelectOptionItem, b: SelectOptionItem, info: { searchValue: string }) => number | — |
| optionFilterProp | 文本与选项的哪些字段匹配(不区分大小写的“包含”)。label 为选项文本;多个字段按“或”匹配。 | string | string[] | 'label' |
| autoClearSearchValue | multiple 与 tags:选择后清空搜索文本。 | boolean | true |
| maxTagCount | multiple 与 tags:只显示这么多标签,其余折叠为一个 + N ... 标签。'responsive':单行显示,能放下多少就显示多少。 | number | 'responsive' | — |
| maxTagPlaceholder | 折叠标签的内容;snippet 会收到被省略的选项。 | string | Snippet<[omitted: SelectOptionItem[]]> | — |
| maxTagTextLength | 较长的标签文本会以省略号截断(其删除按钮的可访问名称保留完整文本)。 | number | — |
| maxCount | multiple 与 tags:最多这么多个值;达到上限后其余选项被禁用。单选模式无效。 | number | — |
| tokenSeparators | multiple 与 tags:输入或粘贴的文本按这些字符拆分为多个值。tags 中每一部分都是值;multiple 中没有匹配选项的部分会被丢弃。超过 maxCount 的值也会被丢弃。 | string[] | [] |
| tagRender | 自定义标签。字段或选项被禁用时 closable 为 false;onclose 移除该值。若自定义关闭控件是 button,点击它不会打开列表。 | Snippet<[tag: { value: SelectValue; label: string | number | Snippet; closable: boolean; onclose: () => void }]> | — |
| optionRender | 列表中选项的内容;字段仍使用普通标签。 | Snippet<[option: SelectOptionItem, index: number]> | — |
| labelRender | 字段中已选值及标签的内容。 | Snippet<[option: SelectOptionItem]> | — |
| notFoundContent | 没有选项时显示在面板中。搜索时状态行会朗读同一段文本(取自该元素,因此 snippet 也可使用)。默认文本为 No data。 | string | Snippet | — |
| resultsText | 搜索时播报匹配数量的礼貌状态行文本:默认 1 result、N results。在列表停止变化 300 毫秒后写入,输入法组合结束后也会写入。没有匹配项时,该行朗读 notFoundContent 的文本而不是数字。 | (count: number) => string | — |
| open | 列表是否显示。使用 bind:open 进行受控。禁用的字段不会显示列表。 | boolean | false |
| onopenchange | 用户导致的展开状态变化时调用一次;父组件所做的更改不会触发。 | (open: boolean) => void | — |
| placement | 列表偏好的方位;在屏幕边缘会翻转,在从右到左的布局中会镜像。 | 'bottomLeft' | 'bottomRight' | 'topLeft' | 'topRight' | 'bottomLeft' |
| popupMatchSelectWidth | true:列表不窄于字段。数字:该宽度(px),但不会比字段窄。false:与内容同宽。 | boolean | number | true |
| listHeight | 列表最大高度(px),超出后滚动。长列表会渲染全部选项(暂无虚拟滚动)。 | number | 256 |
| container | 面板放置的位置:元素,或接收字段并返回元素的函数。位于另一个弹层中的 Select 应传入其字段的父元素。 | HTMLElement | ((anchor: HTMLElement | null) => HTMLElement) | — |
| popupRender | 用你自己的内容包裹列表。在新增内容中点击不会夺走字段的焦点(其中的输入框仍可使用)。 | Snippet<[list: Snippet]> | — |
| defaultActiveFirstOption | 列表打开或过滤变化时高亮第一项。单选字段打开时无论如何都会高亮其已选项。 | boolean | true |
| onchange | 用户每次更改时调用一次,参数为新值与选项对象;父组件所做的更改不会触发。清除后两者均为 undefined(单选)或 []。新标签为 { value: text, label: text }。 | (value: SelectValue | SelectValue[] | undefined, option: SelectOptionItem | SelectOptionItem[] | undefined) => void | — |
| onselect | 选中了一个值。先于 onchange 执行。 | (value: SelectValue, option: SelectOptionItem) => void | — |
| ondeselect | multiple 与 tags:移除了一个值。先于 onchange 执行。 | (value: SelectValue, option: SelectOptionItem) => void | — |
| onclear | 清除按钮清空值之后调用(在 onchange 之后)。 | () => void | — |
| onfocus | 焦点进入字段。在字段、其清除按钮与其面板之间移动不算。 | (event: FocusEvent) => void | — |
| onblur | 焦点离开字段(列表随之关闭)。 | (event: FocusEvent) => void | — |
| onpopupscroll | 列表发生了滚动。 | (event: Event) => void | — |
| oninputkeydown | 焦点元素上有按键按下,早于字段自身的处理。 | (event: KeyboardEvent) => void | — |
| onkeydown / oninput | 焦点元素的原生处理函数;先于组件自身的处理函数调用(oninput 仅在可搜索时有效)。 | (event) => void | — |
| autocomplete | 搜索输入框的 autocomplete。默认的 new-password 可避免浏览器在搜索框中提示已保存的值。 | string | 'new-password' |
| children | 以标记书写的 SelectOption 与 SelectOptGroup;options 非空时被忽略。 | Snippet | — |
| classNames | 各部分的额外类名,追加在组件自身类名之后。popup、list 与 listItem 位于面板中。 | Partial<Record<'root' | 'prefix' | 'content' | 'placeholder' | 'item' | 'clear' | 'input' | 'suffix' | 'popup' | 'list' | 'listItem', string>> | — |
| styles | 各部分的内联样式。属性名为 kebab-case 或自定义属性,数字按原样写入(不自动加 px)。优先于组件自身样式。 | Partial<Record<'root' | 'prefix' | 'content' | 'placeholder' | 'item' | 'clear' | 'input' | 'suffix' | 'popup' | 'list' | 'listItem', Record<string, string | number>>> | — |
| class | 根元素附加的 CSS 类名。字段与 Input 一样撑满容器;宽度请通过 class 或 style 设置。 | string | — |
| style | 根元素的内联样式;styles.root 写在其后。 | string | — |
| native attributes | id(使 <label for> 生效)、aria-label、aria-labelledby、aria-describedby、aria-invalid、tabindex、title、data-* 及其他属性会传给获得焦点的元素。role、aria-expanded、aria-controls、aria-activedescendant、aria-autocomplete 与 aria-busy 由组件管理。 | HTMLAttributes<HTMLElement> | — |
与 Ant Design 的差异:
showSearch 是布尔值,搜索相关属性是平铺的(filterOption、searchValue、onsearch ……),而 React 6 将它们嵌套在对象中;没有 defaultValue 与 defaultOpen,由 bind: 替代;suffix 取代 suffixIcon 与 showArrow;值为字符串或数字(暂无 labelInValue);列表暂不虚拟化,超长列表会渲染全部选项(计划提供 virtual);内置文本(No data、Clear、Remove …)为英文(计划提供本地化机制);字段与 Input 一样撑满容器;选项对象的类型是 SelectOptionItem,因为 SelectOption 是组件名。SelectOption 的 API
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| value | 选项的值;必填,且在 Select 内唯一。 | SelectValue | — |
| label | 绘制的内容,也是搜索与键入定位所用的选项文本:字符串;snippet 仅用于绘制;其次 title,再次是值。 | string | number | Snippet | — |
| disabled | 选项会显示,但方向键会跳过它,且不可选择。 | boolean | — |
| title | 选项的原生 title;当 label 不是字符串时也作为其文本。 | string | — |
| class | 选项在列表中的额外类名。 | string | — |
| children | 列表项的内容。同时给出 label 时绘制此内容,文本仍为 label。 | Snippet | — |
SelectOptGroup 的 API
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| label | 分组标题;为辅助技术命名该分组。它不是选项。 | string | number | Snippet | — |
| title | 分组标题的原生 title。 | string | — |
| class | 分组的额外类名。 | string | — |
| children | 该分组的 SelectOption。 | Snippet | — |
方法
通过 bind:this 调用。聚焦时不会打开列表。
| 方法 | 说明 | 类型 |
|---|---|---|
| focus | 使焦点进入字段(可搜索时为文本框)。不会打开列表。 | (options?: { preventScroll?: boolean }) => void |
| blur | 让字段失焦;列表随之关闭。 | () => void |
设计令牌
| 令牌 | 说明 | 默认值 |
|---|---|---|
| --ads-select-icon-size | 箭头、清除图标与已选选项标记的尺寸。 | 12px |
| --ads-select-gap | 文本与箭头或清除按钮之间的距离。 | 6px |
| --ads-select-multiple-padding-block | 带标签字段的垂直内边距;与标签高度一起,单行时得到各尺寸的 40、32、24px 高度。 | 3px |
| --ads-select-multiple-padding-inline | 带标签字段的水平内边距。 | 4px |
| --ads-select-tag-height | 中号字段中标签的高度。 | 24px |
| --ads-select-tag-height-lg | 大号字段中标签的高度。 | 32px |
| --ads-select-tag-height-sm | 小号字段中标签的高度。 | 16px |
| --ads-select-tag-radius | 标签圆角半径。 | 4px |
| --ads-select-tag-gap | 标签之间、标签行之间以及删除图标之前的距离。 | 4px |
| --ads-select-tag-padding-start | 标签起始侧的内边距,以及折叠标签两端的内边距。 | 8px |
| --ads-select-tag-padding-end | 标签末尾(删除图标之后)的内边距。 | 4px |
| --ads-select-tag-remove-size | 标签删除图标的尺寸。 | 10px |
| --ads-select-tag-bg | 标签背景。 | rgba(0, 0, 0, 0.06) |
| --ads-select-tag-border | 标签边框颜色(在强制颜色模式下可见)。 | transparent |
| --ads-select-tag-color-disabled | 不可移除标签的文本颜色。 | rgba(0, 0, 0, 0.25) |
| --ads-select-popup-padding | 面板中列表周围的内边距。 | 4px |
| --ads-select-popup-radius | 面板圆角半径。 | 8px |
| --ads-select-popup-bg | 面板背景。 | #ffffff |
| --ads-select-popup-shadow | 面板阴影。 | 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) |
| --ads-select-option-radius | 选项圆角半径。 | 4px |
| --ads-select-option-height | 选项的最小高度。 | 32px |
| --ads-select-option-font-size | 列表字号。 | 14px |
| --ads-select-option-line-height | 列表行高。 | 1.5714285714285714 |
| --ads-select-option-padding-block | 选项的垂直内边距。 | 5px |
| --ads-select-option-padding-inline | 选项与分组标题的水平内边距。 | 12px |
| --ads-select-option-gap | 选项之间的距离。 | 2px |
| --ads-select-option-active-bg | 高亮选项的背景。 | rgba(0, 0, 0, 0.04) |
| --ads-select-option-selected-bg | 已选选项的背景。 | #e6f4ff |
| --ads-select-option-selected-color | 已选选项的文本颜色。 | rgba(0, 0, 0, 0.88) |
| --ads-select-selected-font-weight | 已选选项的字重。 | 600 |
| --ads-select-group-font-size | 分组标题字号。 | 12px |
| --ads-select-group-label-color | 分组标题的文本颜色(无障碍色值文件会将其加深)。 | rgba(0, 0, 0, 0.45) |
| --ads-select-empty-color | 无结果文本的颜色(无障碍色值文件会将其加深)。 | rgba(0, 0, 0, 0.45) |
无障碍
- 获得焦点的元素带有
role="combobox",以及aria-expanded、aria-controls与aria-activedescendant;列表是由option与group组成的listbox。DOM 焦点始终不离开字段:高亮选项通过aria-activedescendant呈现。 - 必须提供名称:
<label for>、aria-label或aria-labelledby。占位符不是名称。列表沿用字段的名称。 - 按键:Down、Up、Alt+Down 与 Alt+Up、Enter 与 Space、Home 与 End、PageUp 与 PageDown、Escape、Tab 与 Backspace。不可搜索的字段还可通过键入选项文本的开头来定位。Tab 只会关闭列表并保留当前值。
- 已选选项带有
aria-selected="true",禁用选项带有aria-disabled。搜索时,一条礼貌的状态行会播报匹配数量;没有匹配项时则播报无结果文本。 - 清除与删除按钮是名为
Clear与Remove …的原生按钮,不会夺走字段焦点。图标对辅助技术隐藏。支持强制颜色模式(Windows 高对比度)。 - 默认的浅色值来自 Ant Design,部分文本达不到 WCAG AA;请引入
tokens-accessible.css以获得达标的颜色。深色主题无需该文件即可满足 AA。 - iOS VoiceOver 对
aria-activedescendant的支持一直较弱,请在该平台上手动检查 Select 后再依赖它。 - 已知限制:Orca 仅在按下空格键后播报
aria-selected的变化。在可搜索的字段中(multiple与tags的默认模式),空格键用于输入空格,切换选项靠回车,因此 Orca 不会播报;字段在获得焦点时会朗读已选值。此外,Orca 不会朗读不可搜索的多值字段(showSearch={false})的已选值。NVDA、JAWS 与 VoiceOver 尚未测试。切换选项的播报计划在 v1.1 中随内置文本的翻译一并提供。