选择浮层列表中的一个或多个值。
当人们需要从一组选项中做选择时,就使用 Select。它负责打开列表、键盘导航、选择,以及随表单提交的值。你负责提供部件和样式。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
const roles = [
{ value: "viewer", label: "Viewer" },
{ value: "commenter", label: "Commenter" },
{ value: "editor", label: "Editor" },
{ value: "admin", label: "Admin" },
]
function Example() {
return (
<Field>
<FieldLabel>Role</FieldLabel>
<Select placeholder="Select a role">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{roles.map((role) => (
<SelectItem key={role.value} value={role.value}>
{role.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)
}
export { Example }安装
npm install @ui-sdk/react @ui-sdk/core组合
用下面的组合构建 Select:
Select
├── SelectLabel
├── SelectTrigger
│ └── SelectValue
└── SelectContent
├── SelectItem
└── SelectItem从标签、触发器和选项列表开始。SelectValue 在触发器里显示选中选项的标签。SelectLabel 为触发器命名;在 Field 里,改用它的 FieldLabel,示例就是这样做的。
用法
导入部件并把它们组合起来:
import {
Select,
SelectContent,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
function Example() {
return (
<Select placeholder="Select a role">
<SelectLabel>Role</SelectLabel>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="viewer">Viewer</SelectItem>
<SelectItem value="editor">Editor</SelectItem>
</SelectContent>
</Select>
)
}
export { Example }以数据形式提供的选项
当选项来自数据时,把数组传给 items。字符串既是值也是标签。两者不同时,使用对象:
<Select items={["Free", "Pro"]} />
<Select items={[{ value: "pro", label: "Pro plan" }]} />这些是选项示例;补上前面展示的标签和触发器。items 还可以包含分组和分隔符,用 ListData 检查:
import type { ListData } from "@ui-sdk/react/select"
const plans: ListData = [
{ value: "free", label: "Free" },
{ type: "separator" },
{ type: "group", label: "Contact sales", items: ["Enterprise"] },
]Select 可以直接渲染这份数据中的选项本身。要为它们设置样式,就把 items 留在 Select 上,并在 SelectContent 里渲染 SelectItem 部件,示例就是这样做的。把数据放在根部件上,还能让标签在列表打开之前就可用,包括服务端渲染期间。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectGroup,
SelectGroupLabel,
SelectItem,
SelectItemIndicator,
SelectSeparator,
SelectTrigger,
SelectValue,
type ListData,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
const plans = [
{ value: "free", label: "Free" },
{ value: "pro", label: "Pro" },
{ value: "team", label: "Team" },
]
const sales = [
{ value: "enterprise", label: "Enterprise" },
{ value: "education", label: "Education", disabled: true },
]
const items: ListData = [
...plans,
{ type: "separator" },
{ type: "group", label: "Contact sales", items: sales },
]
function Example() {
return (
<Field>
<FieldLabel>Plan</FieldLabel>
<Select items={items} defaultValue="pro">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{plans.map((plan) => (
<SelectItem key={plan.value} value={plan.value}>
{plan.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
<SelectSeparator />
<SelectGroup>
<SelectGroupLabel>Contact sales</SelectGroupLabel>
{sales.map((plan) => (
<SelectItem
key={plan.value}
value={plan.value}
disabled={plan.disabled}
>
{plan.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
</Field>
)
}
export { Example }列表打开期间,选项可以变化。导航跟随新的顺序;对应的选项还在时,它的选中和高亮状态保持不变。移除高亮的选项会清除高亮。列表与菜单介绍了共享的数据结构。
分组
把相关的选项放进 SelectGroup,用 SelectGroupLabel 为每个分组命名。SelectSeparator 添加一条视觉分隔,本身不会成为选项。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectGroup,
SelectGroupLabel,
SelectItem,
SelectItemIndicator,
SelectSeparator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
import * as React from "react"
const fonts = [
{
label: "Sans serif",
items: [
{ value: "inter", label: "Inter" },
{ value: "geist", label: "Geist" },
],
},
{
label: "Serif",
items: [
{ value: "source-serif", label: "Source Serif" },
{ value: "lora", label: "Lora" },
],
},
{
label: "Monospace",
items: [
{ value: "geist-mono", label: "Geist Mono" },
{ value: "jetbrains-mono", label: "JetBrains Mono" },
],
},
]
function Example() {
return (
<Field>
<FieldLabel>Font</FieldLabel>
<Select placeholder="Select a font">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{fonts.map((group, index) => (
<React.Fragment key={group.label}>
{index > 0 && <SelectSeparator />}
<SelectGroup>
<SelectGroupLabel>{group.label}</SelectGroupLabel>
{group.items.map((item) => (
<SelectItem key={item.value} value={item.value}>
{item.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectGroup>
</React.Fragment>
))}
</SelectContent>
</Select>
</Field>
)
}
export { Example }图标
SelectItemIcon 让图标与选项的文本分开,因此不影响它的无障碍名称、键入查找(typeahead)或搜索。把 SelectValueIcon 加到触发器上,选中选项的图标也会显示在那里。
<SelectTrigger>
<SelectValueIcon />
<SelectValue />
</SelectTrigger>完整示例用 mirror 标记方向性图标,让它们在从右到左(RTL)的布局中翻转。只包含图标的选项仍然需要 aria-label。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIcon,
SelectItemIndicator,
SelectTrigger,
SelectValue,
SelectValueIcon,
} from "@ui-sdk/react/select"
import {
CheckIcon,
ChevronDownIcon,
TextAlignCenterIcon,
TextAlignEndIcon,
TextAlignStartIcon,
} from "lucide-react"
function Example() {
return (
<Field>
<FieldLabel>Text alignment</FieldLabel>
<Select defaultValue="start">
<SelectTrigger>
<SelectValueIcon />
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
<SelectItem value="start">
<SelectItemIcon mirror>
<TextAlignStartIcon />
</SelectItemIcon>
Start
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
<SelectItem value="center">
<SelectItemIcon>
<TextAlignCenterIcon />
</SelectItemIcon>
Center
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
<SelectItem value="end">
<SelectItemIcon mirror>
<TextAlignEndIcon />
</SelectItemIcon>
End
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
</SelectContent>
</Select>
</Field>
)
}
export { Example }键入查找
触发器获得焦点且列表关闭时,输入内容会选择下一个匹配的选项,而不打开列表。列表打开时,输入会移动高亮;Enter 选择高亮的选项。
当选项内容包含不应参与匹配的额外文本时,设置它的 label。这里国家名称参与键入匹配,电话区号不参与。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
const countries = [
{ value: "ar", label: "Argentina", code: "+54" },
{ value: "au", label: "Australia", code: "+61" },
{ value: "at", label: "Austria", code: "+43" },
{ value: "be", label: "Belgium", code: "+32" },
{ value: "br", label: "Brazil", code: "+55" },
{ value: "ca", label: "Canada", code: "+1" },
{ value: "dk", label: "Denmark", code: "+45" },
{ value: "fr", label: "France", code: "+33" },
{ value: "de", label: "Germany", code: "+49" },
{ value: "gr", label: "Greece", code: "+30" },
{ value: "ie", label: "Ireland", code: "+353" },
{ value: "jp", label: "Japan", code: "+81" },
{ value: "es", label: "Spain", code: "+34" },
{ value: "se", label: "Sweden", code: "+46" },
{ value: "ch", label: "Switzerland", code: "+41" },
]
function Example() {
return (
<Field>
<FieldLabel>Country</FieldLabel>
<Select defaultValue="fr">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{countries.map((country) => (
<SelectItem
key={country.value}
value={country.value}
label={country.label}
>
{country.label}
<span data-slot="hint">{country.code}</span>
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)
}
export { Example }禁用
禁用的 Select 无法聚焦或更改,也不会提交值。只读的 Select 保持可聚焦并提交它的值,但无法更改。键盘导航会跳过禁用的选项,它们也无法被选中。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
const countries = [
{ value: "ca", label: "Canada" },
{ value: "dk", label: "Denmark" },
{ value: "fr", label: "France" },
{ value: "de", label: "Germany" },
{ value: "jp", label: "Japan" },
{ value: "es", label: "Spain" },
]
const fields = [
{ label: "Billing country", disabled: true },
{ label: "Shipping from", readOnly: true },
{ label: "Shipping to" },
]
function Example() {
return (
<div data-slot="stack">
{fields.map((field) => (
<Field key={field.label}>
<FieldLabel>{field.label}</FieldLabel>
<Select
defaultValue={field.disabled || field.readOnly ? "fr" : null}
placeholder="Select a country"
disabled={field.disabled}
readOnly={field.readOnly}
>
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{countries.map((country) => (
<SelectItem
key={country.value}
value={country.value}
disabled={country.value === "dk"}
>
{country.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
))}
</div>
)
}
export { Example }清除按钮
没有选中任何内容时,placeholder 会显示。添加 SelectClear 可以回到这个状态。清除会把单值设为 null,把多值设为空数组,并把焦点返回触发器。
把清除按钮放在触发器旁边:按钮不能包含另一个按钮。keepMounted 让它在没有内容可清除时仍留在 DOM 中。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectClear,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon, XIcon } from "lucide-react"
import { useLog } from "./log"
const people = [
{ value: "hollis", label: "Hollis Grant" },
{ value: "ines", label: "Inès Moreau" },
{ value: "kofi", label: "Kofi Mensah" },
{ value: "wren", label: "Wren Takahashi" },
{ value: "tomasz", label: "Tomasz Wójcik" },
]
function Example() {
const log = useLog()
return (
<Field>
<FieldLabel>Assignee</FieldLabel>
<Select
defaultValue="ines"
placeholder="Unassigned"
onValueChange={(value, details) =>
log(`value: ${JSON.stringify(value)} (${details.reason})`)
}
>
<div data-slot="row">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectClear aria-label="Clear assignee">
<XIcon />
</SelectClear>
</div>
<SelectContent>
{people.map((person) => (
<SelectItem key={person.value} value={person.value}>
{person.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)
}
export { Example }多选
设置 multiple 可以选择多个值。值会变成数组,选择某个选项会切换它,同时保持列表打开。
<Select multiple defaultValue={["en", "ja"]} />SelectValue 把选中的 labels 暴露给它的 children 函数。用它们概括一长串选择,示例就是这样做的。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
import { useLog } from "./log"
const languages = [
{ value: "en", label: "English" },
{ value: "fr", label: "French" },
{ value: "de", label: "German" },
{ value: "ja", label: "Japanese" },
{ value: "pt", label: "Portuguese" },
{ value: "es", label: "Spanish" },
]
function Example() {
const log = useLog()
return (
<Field>
<FieldLabel>Languages</FieldLabel>
<Select
multiple
defaultValue={["en", "ja"]}
placeholder="Select languages"
onValueChange={(value) => log(`value: ${JSON.stringify(value)}`)}
>
<SelectTrigger>
<SelectValue>
{(state) =>
state.placeholder
? "Select languages"
: state.labels.length > 2
? `${state.labels[0]} and ${state.labels.length - 1} more`
: state.label
}
</SelectValue>
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{languages.map((language) => (
<SelectItem key={language.value} value={language.value}>
{language.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)
}
export { Example }全选
添加 SelectSelectAll 可以选择或清除每个已启用的选项。只有部分选中时,它显示混合状态。放在 SelectGroup 内部时,它只作用于那个分组。
SelectValue maxLabels={2} 最多显示两个标签,并概括其余的值。getMoreLabel 让你自己写这段概括。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectSelectAll,
SelectSeparator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon, MinusIcon } from "lucide-react"
const regions = [
{ value: "us-east", label: "US East" },
{ value: "us-west", label: "US West" },
{ value: "europe", label: "Europe" },
{ value: "asia-pacific", label: "Asia Pacific" },
{ value: "south-america", label: "South America" },
]
function Example() {
return (
<Field>
<FieldLabel>Regions</FieldLabel>
<Select
multiple
defaultValue={["us-east", "europe", "asia-pacific"]}
placeholder="Select regions"
>
<SelectTrigger>
<SelectValue
maxLabels={2}
getMoreLabel={(count) => `${count} more`}
/>
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
<SelectSelectAll>
{(state) => (
<>
Select all
{state.checked && <CheckIcon />}
{state.indeterminate && <MinusIcon />}
</>
)}
</SelectSelectAll>
<SelectSeparator />
{regions.map((region) => (
<SelectItem key={region.value} value={region.value}>
{region.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)
}
export { Example }带分组的搜索
在 SelectContent 里添加 SelectInput 来过滤选项。把选项放进 SelectList,这样搜索字段就留在可滚动列表之外。没有匹配项时显示 SelectEmpty。
<SelectContent>
<SelectInput aria-label="Search countries" />
<SelectEmpty>No countries found.</SelectEmpty>
<SelectList>{/* Items go here. */}</SelectList>
</SelectContent>没有匹配选项的分组会自动隐藏。SelectItemText 可以高亮匹配的文本;这个示例用它的 segments 把匹配项加粗。关闭浮层会清除搜索。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectEmpty,
SelectGroup,
SelectGroupLabel,
SelectInput,
SelectItem,
SelectItemIndicator,
SelectItemText,
SelectList,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
const regions = [
{
label: "Americas",
items: [
{ value: "br", label: "Brazil" },
{ value: "ca", label: "Canada" },
{ value: "mx", label: "Mexico" },
],
},
{
label: "Europe",
items: [
{ value: "fr", label: "France" },
{ value: "de", label: "Germany" },
{ value: "es", label: "Spain" },
],
},
{
label: "Asia Pacific",
items: [
{ value: "au", label: "Australia" },
{ value: "jp", label: "Japan" },
{ value: "sg", label: "Singapore" },
],
},
]
function Example() {
return (
<Field>
<FieldLabel>Country</FieldLabel>
<Select placeholder="Select a country">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
<SelectInput
aria-label="Search countries"
placeholder="Search countries…"
/>
<SelectEmpty>No countries found.</SelectEmpty>
<SelectList>
{regions.map((group) => (
<SelectGroup key={group.label}>
<SelectGroupLabel>{group.label}</SelectGroupLabel>
{group.items.map((item) => (
<SelectItem
key={item.value}
value={item.value}
label={item.label}
>
<SelectItemText>
{(state) =>
state.segments.map((segment, index) =>
segment.match ? (
<b key={index}>{segment.text}</b>
) : (
segment.text
)
)
}
</SelectItemText>
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectGroup>
))}
</SelectList>
</SelectContent>
</Select>
</Field>
)
}
export { Example }方向键移动高亮,焦点留在搜索字段里。在触摸屏的屏幕阅读器上,焦点会改为移入选项。要在搜索之前显示最近的选择,把 emptyItems 和 items 一起传入。列表与菜单介绍了选项过滤。
异步搜索
服务器已经在过滤选项时,使用 filter={false}。把 query 和 onQueryChange 接到你的加载函数上,并把它的选项和状态传给 Select。
这个示例用异步选项替换过期的请求,并通过 onLoadMore 加载下一页。SelectStatus 显示加载状态和结果数量。没有状态部件时,Select 通过页面的实时区域(live region)播报结果数量。
"use client"
import { useAsyncOptions } from "@ui-sdk/react/async-options"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectEmpty,
SelectInput,
SelectItem,
SelectItemIndicator,
SelectList,
SelectStatus,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
import * as React from "react"
const countryList = [
{ value: "ar", label: "Argentina" },
{ value: "au", label: "Australia" },
{ value: "at", label: "Austria" },
{ value: "be", label: "Belgium" },
{ value: "br", label: "Brazil" },
{ value: "ca", label: "Canada" },
{ value: "cl", label: "Chile" },
{ value: "cn", label: "China" },
{ value: "dk", label: "Denmark" },
{ value: "fi", label: "Finland" },
{ value: "fr", label: "France" },
{ value: "de", label: "Germany" },
{ value: "gr", label: "Greece" },
{ value: "in", label: "India" },
{ value: "ie", label: "Ireland" },
{ value: "it", label: "Italy" },
{ value: "jp", label: "Japan" },
{ value: "mx", label: "Mexico" },
{ value: "nl", label: "Netherlands" },
{ value: "no", label: "Norway" },
{ value: "pt", label: "Portugal" },
{ value: "es", label: "Spain" },
{ value: "se", label: "Sweden" },
{ value: "ch", label: "Switzerland" },
]
function searchCountries(
query: string,
{ signal, page }: { signal: AbortSignal; page: number }
) {
return new Promise<{ items: typeof countryList; hasMore: boolean }>(
(resolve, reject) => {
const timer = setTimeout(() => {
const needle = query.trim().toLowerCase()
const found = countryList.filter((country) =>
country.label.toLowerCase().includes(needle)
)
resolve({
items: found.slice(page * 6, page * 6 + 6),
hasMore: found.length > page * 6 + 6,
})
}, 400)
signal.addEventListener("abort", () => {
clearTimeout(timer)
reject(signal.reason)
})
}
)
}
function Example() {
const [query, setQuery] = React.useState("")
const results = useAsyncOptions(searchCountries, { immediate: true })
return (
<Field>
<FieldLabel>Country</FieldLabel>
<Select
items={results.items}
filter={false}
status={results.status}
query={query}
onQueryChange={(next) => {
setQuery(next)
results.setQuery(next)
}}
onLoadMore={results.loadMore}
placeholder="Select a country"
>
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
<SelectInput
aria-label="Search countries"
placeholder="Search countries…"
/>
<SelectEmpty>
{(state) =>
state.empty && !state.loading
? `No countries match “${state.query}”.`
: null
}
</SelectEmpty>
<SelectList>
{(state) =>
(
state.items as {
value: string
label: string
disabled?: boolean
}[]
).map((item) => (
<SelectItem
key={item.value}
value={item.value}
label={item.label}
disabled={item.disabled}
>
{item.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))
}
</SelectList>
<SelectStatus>
{(state) =>
state.loading
? "Loading…"
: state.status === "error"
? "Couldn't load countries."
: `${state.count} shown`
}
</SelectStatus>
</SelectContent>
</Select>
</Field>
)
}
export { Example }对象值
值可以是对象。告诉 Select 如何识别它、显示它,以及如何与另一份副本比较:
| 属性 | 作用 |
|---|---|
itemToValue | 返回用于标识和提交该值的字符串。 |
itemToLabel | 返回触发器中显示的文本。 |
isItemEqualToValue | 把选项与选中值匹配,即使后者可能是另一份不同的对象。 |
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
import { useLog } from "./log"
type Member = { id: number; name: string; email: string }
const members: Member[] = [
{ id: 1, name: "Hollis Grant", email: "hollis@example.com" },
{ id: 2, name: "Inès Moreau", email: "ines@example.com" },
{ id: 3, name: "Kofi Mensah", email: "kofi@example.com" },
{ id: 4, name: "Wren Takahashi", email: "wren@example.com" },
]
function Example() {
const log = useLog()
return (
<Field>
<FieldLabel>Assignee</FieldLabel>
<Select
defaultValue={{ ...members[1] }}
onValueChange={(member) =>
log(`Submits assignee=${member ? member.id : ""}`)
}
name="assignee"
itemToValue={(member) => String(member.id)}
itemToLabel={(member) => member.name}
isItemEqualToValue={(item, value) => item.id === value.id}
placeholder="Unassigned"
>
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{members.map((member) => (
<SelectItem key={member.id} value={member}>
<span data-slot="stack">
{member.name}
<span data-slot="hint">{member.email}</span>
</span>
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)
}
export { Example }虚拟化
对于长列表,通过 items 传入每个选项,只渲染可见的行。onHighlight 告诉虚拟化器把哪一行带入视图。给每个渲染的选项传入它在完整列表中的 index,无障碍属性才能正确描述它的位置。
这个示例自带几个小的行窗口辅助函数。你也可以把同样的 props 用在你选择的虚拟化器上。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectList,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import * as React from "react"
import { ChevronDownIcon } from "lucide-react"
const manyItems = Array.from({ length: 10_000 }, (_, index) => ({
value: `item-${index + 1}`,
label: `Item ${index + 1}`,
}))
function visibleRows(
scrollTop: number,
height: number,
count: number,
row: number
) {
const start = Math.max(0, Math.floor(scrollTop / row) - 4)
const end = Math.min(count, Math.ceil((scrollTop + height) / row) + 4)
return { start, end }
}
function scrollForRow(
index: number,
scrollTop: number,
height: number,
row: number
) {
const top = index * row
if (top < scrollTop) {
return top
}
if (top + row > scrollTop + height) {
return top + row - height
}
return scrollTop
}
const row = 32
const height = 288
function Example() {
const scroller = React.useRef<HTMLDivElement>(null)
const [scrollTop, setScrollTop] = React.useState(0)
return (
<Field>
<FieldLabel>Item</FieldLabel>
<Select
items={manyItems}
placeholder="Select an item"
onHighlight={(value, { index }) => {
const el = scroller.current
if (el && index >= 0) {
el.scrollTop = scrollForRow(
index,
el.scrollTop,
el.clientHeight,
row
)
}
}}
>
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
<div
ref={scroller}
style={{ height }}
onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
>
<SelectList>
{(state) => {
const items = state.items as { value: string; label: string }[]
const { start, end } = visibleRows(
scrollTop,
height,
items.length,
row
)
return (
<div style={{ height: items.length * row }}>
{items.slice(start, end).map((item, offset) => (
<SelectItem
key={item.value}
value={item.value}
label={item.label}
index={start + offset}
style={{ top: (start + offset) * row, height: row }}
>
{item.label}
</SelectItem>
))}
</div>
)
}}
</SelectList>
</div>
</SelectContent>
</Select>
</Field>
)
}
export { Example }让选项与触发器对齐
在 SelectContent 上设置 alignItemWithTrigger,把选中的选项放在触发器上方。通过触摸打开或空间不足时,它会回退到普通的浮层放置方式。
"use client"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/react/checkbox"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
import * as React from "react"
const priorities = [
{ value: "urgent", label: "Urgent" },
{ value: "high", label: "High" },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
{ value: "none", label: "No priority" },
]
function Example() {
const [aligned, setAligned] = React.useState(true)
return (
<div data-slot="stack">
<div data-slot="controls">
<label data-slot="label">
<Checkbox
checked={aligned}
onCheckedChange={(next) => setAligned(next === true)}
>
<CheckboxIndicator>
<CheckIcon />
</CheckboxIndicator>
</Checkbox>
Align item with trigger
</label>
</div>
<Field>
<FieldLabel>Priority</FieldLabel>
<Select defaultValue="medium">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent alignItemWithTrigger={aligned}>
{priorities.map((priority) => (
<SelectItem key={priority.value} value={priority.value}>
{priority.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
</div>
)
}
export { Example }可滚动
限制内容的高度并允许纵向滚动。--available-height 告诉你浮层有多少空间;用键盘移动时,高亮的选项会滚动到视图中。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectGroup,
SelectGroupLabel,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
const timezones = [
{
label: "North America",
items: [
{ value: "est", label: "Eastern Standard Time" },
{ value: "cst", label: "Central Standard Time" },
{ value: "mst", label: "Mountain Standard Time" },
{ value: "pst", label: "Pacific Standard Time" },
{ value: "akst", label: "Alaska Standard Time" },
{ value: "hst", label: "Hawaii Standard Time" },
],
},
{
label: "Europe & Africa",
items: [
{ value: "gmt", label: "Greenwich Mean Time" },
{ value: "cet", label: "Central European Time" },
{ value: "eet", label: "Eastern European Time" },
{ value: "west", label: "Western European Summer Time" },
{ value: "cat", label: "Central Africa Time" },
{ value: "eat", label: "East Africa Time" },
],
},
{
label: "Asia",
items: [
{ value: "msk", label: "Moscow Time" },
{ value: "ist", label: "India Standard Time" },
{ value: "cst-china", label: "China Standard Time" },
{ value: "jst", label: "Japan Standard Time" },
{ value: "kst", label: "Korea Standard Time" },
{ value: "ist-indonesia", label: "Indonesia Central Standard Time" },
],
},
{
label: "Australia & Pacific",
items: [
{ value: "awst", label: "Australian Western Standard Time" },
{ value: "acst", label: "Australian Central Standard Time" },
{ value: "aest", label: "Australian Eastern Standard Time" },
{ value: "nzst", label: "New Zealand Standard Time" },
{ value: "fjt", label: "Fiji Time" },
],
},
]
function Example() {
return (
<Field>
<FieldLabel>Time zone</FieldLabel>
<Select placeholder="Select a time zone">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{timezones.map((group) => (
<SelectGroup key={group.label}>
<SelectGroupLabel>{group.label}</SelectGroupLabel>
{group.items.map((item) => (
<SelectItem key={item.value} value={item.value}>
{item.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectGroup>
))}
</SelectContent>
</Select>
</Field>
)
}
export { Example }无效
在 Field 内部,字段的标签为触发器命名,它的描述和错误信息描述触发器,提交时使用它的 name。无效提交之后,触发器会得到 aria-invalid 和 data-invalid。
"use client"
import {
Field,
FieldDescription,
FieldError,
FieldLabel,
} from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
import { useLog } from "./log"
const methods = [
{ value: "standard", label: "Standard" },
{ value: "express", label: "Express" },
{ value: "overnight", label: "Overnight" },
]
function Example() {
const log = useLog()
return (
<form
data-slot="stack"
onSubmit={(event) => {
event.preventDefault()
log(
`Submitted shipping=${new FormData(event.currentTarget).get("shipping")}`
)
}}
>
<Field name="shipping">
<FieldLabel>Shipping method</FieldLabel>
<Select required placeholder="Select a shipping method">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{methods.map((method) => (
<SelectItem key={method.value} value={method.value}>
{method.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
<FieldDescription>
Express arrives in two business days.
</FieldDescription>
<FieldError match="valueMissing">Choose a shipping method.</FieldError>
</Field>
<button type="submit" data-variant="solid">
Continue
</button>
</form>
)
}
export { Example }表单
设置 name 让 Select 参与表单提交。required 在选中内容之前阻止提交;重置表单会恢复 defaultValue。多个值会以独立条目提交在同一个名称下。
这个示例还用 autoComplete="country" 实现自动填充,并用 form="select-newsletter" 把 Frequency 的 Select 关联到它外部的表单。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
import { useLog } from "./log"
const countries = [
{ value: "au", label: "Australia" },
{ value: "br", label: "Brazil" },
{ value: "ca", label: "Canada" },
{ value: "fr", label: "France" },
{ value: "de", label: "Germany" },
{ value: "jp", label: "Japan" },
{ value: "es", label: "Spain" },
{ value: "se", label: "Sweden" },
]
const topics = ["Design", "Engineering", "Marketing", "Research", "Sales"]
const frequencies = ["Daily", "Weekly", "Monthly"]
function Example() {
const log = useLog()
return (
<div data-slot="stack">
<form
id="select-newsletter"
data-slot="stack"
onSubmit={(event) => {
event.preventDefault()
const entries = [...new FormData(event.currentTarget)].map(
([name, value]) => `${name}=${value}`
)
log(`Submitted ${entries.join("&")}`)
}}
>
<Field>
<FieldLabel>Country</FieldLabel>
<Select
name="country"
autoComplete="country"
required
placeholder="Select a country"
>
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{countries.map((country) => (
<SelectItem key={country.value} value={country.value}>
{country.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel>Topics</FieldLabel>
<Select name="topics" multiple defaultValue={["Design"]}>
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{topics.map((topic) => (
<SelectItem key={topic} value={topic}>
{topic}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
</form>
<Field>
<FieldLabel>Frequency</FieldLabel>
<Select name="frequency" form="select-newsletter" defaultValue="Weekly">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{frequencies.map((frequency) => (
<SelectItem key={frequency} value={frequency}>
{frequency}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<div data-slot="row">
<button type="submit" form="select-newsletter" data-variant="solid">
Save
</button>
<button type="reset" form="select-newsletter">
Reset
</button>
</div>
</div>
)
}
export { Example }呈现方式
用 presentation="sheet" 在底部面板(sheet)中打开选项,或用 "auto" 在小尺寸触摸屏上使用底部面板。选择选项仍会选中它,并关闭单选列表。
内容会得到 data-presentation,它的渲染状态里也包含 presentation。用其中任意一个给底部面板的选项更多空间。为底部面板保留 translate property,供它的拖动行为使用,并在底部加入安全区域的内边距。
"use client"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectTrigger,
SelectValue,
} from "@ui-sdk/react/select"
import { CheckIcon, ChevronDownIcon } from "lucide-react"
const statuses = [
{ value: "backlog", label: "Backlog" },
{ value: "todo", label: "Todo" },
{ value: "in-progress", label: "In Progress" },
{ value: "in-review", label: "In Review" },
{ value: "done", label: "Done" },
]
function Example() {
return (
<Field>
<FieldLabel>Status</FieldLabel>
<Select defaultValue="todo" presentation="sheet">
<SelectTrigger>
<SelectValue />
<ChevronDownIcon />
</SelectTrigger>
<SelectContent>
{statuses.map((status) => (
<SelectItem key={status.value} value={status.value}>
{status.label}
<SelectItemIndicator>
<CheckIcon />
</SelectItemIndicator>
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)
}
export { Example }除非 modal={false},底部面板会让它后面的页面不可交互(inert),并锁定滚动。浮层解释了共享的呈现方式选项。
受控
用 value 和 onValueChange 掌控选择,用 open 和 onOpenChange 掌控浮层状态。单值是 T | null;使用 multiple 时是 T[]。两个回调都先收到请求的值,再收到变更详情。调用 details.cancel() 拒绝一次变更。
状态与事件解释了这个模式。原因表列出了 Select 的原因,包括 item-press、list-navigation 和 clear-press。
控制器
createSelectController() 可以从组件外部打开、读取或更改 Select。它还能连接一个独立的触发器。设置方法以及等待浮层关闭的写法见控制器,方法列表见 Select 控制器参考。
定位
用 side、align 和偏移量放置浮层。SelectArrow 跟随它最终落在的那一侧。浮层介绍了锚点和碰撞处理。
模态
默认情况下,外部按压会关闭列表,但不会激活它后面的元素。modal={true} 还会锁定滚动,并让页面不可交互(inert)。modal={false} 允许外部按压穿透。见控制关闭。
容器
浮层使用顶层,不需要传送门(portal)。当它必须渲染到另一个 DOM 容器时,使用 container。挂载与容器介绍了共享的设置。
动画
Select 会让正在关闭的内容保持挂载,直到它的退场(outro)动画结束。之后运行 onOpenChangeComplete。如果你的动画库需要已关闭的内容留在 DOM 中,使用 keepMounted。样式与动画介绍了生命周期属性。
自定义渲染
用 render 指定部件渲染的元素,或用状态函数自定义它的 children 或类名。部件与组合解释了 props 如何合并。Select 各部件收到的状态列在状态下。
样式
用 data-highlighted 标记活动选项,用 data-selected 标记选中的选项,没有选中任何内容时在触发器和值上使用 data-placeholder。内容上的 data-modality="keyboard" 区分键盘高亮和指针高亮。
--anchor-width 与触发器宽度一致,--available-height 说明浮层有多少空间。用它们设置内容的尺寸。
每个部件都有一个 data-slot,比如 select-trigger,它的状态属性列在数据属性下。
SelectContent
| 变量 | 内容 |
|---|---|
--anchor-width | Width of the anchor, usually the trigger. Use it to match widths. |
--anchor-height | Height of the anchor. |
--available-width | Space beside the popup, up to the viewport edge. Not inherited either. |
--available-height | Space between the anchor and the viewport edge. Use it for max-height. Not inherited, so a child that needs it copies it on the popup, like [--list-height:var(--available-height)], and reads max-h-(--list-height). The first popup registers both names for the whole page with CSS.registerProperty, so they don't inherit anywhere. A page that needs them to inherit calls it first, with inherits: true. An @property rule can't, since a registration in script wins. |
--transform-origin | The point on the anchor the popup opens from. Use it to scale from the right place. |
--arrow-offset | Where the anchor's center falls along the popup's edge, kept arrowPadding from the corners. Position a ::before arrow with it. |
--drawer-progress | While it presents as a sheet: how far open the sheet is, from 0 closed to 1 at its largest snap point. Never past 1. |
--drawer-dim | While it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it. |
--drawer-expand | While it presents as a sheet: 0 at the second-largest snap point and below, 1 at the largest. With one snap point, the whole travel. |
--drawer-stack | While it presents as a sheet: how many sheets opened from inside this one are open above it, rising smoothly as each one opens. Push it back with it. |
--sheet-backdrop | Set it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default. |
Viewport
| 变量 | 内容 |
|---|---|
--keyboard-inset | While it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one. |
--visual-viewport-width | While it presents as a sheet: the width of the part of the page you can see. |
--visual-viewport-height | While it presents as a sheet: the height of the part of the page you can see, above the keyboard. |
--visual-viewport-top | While it presents as a sheet: how far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up. |
数据属性
SelectList、SelectInput、SelectGroup、SelectGroupLabel、SelectSeparator 和 SelectValueIcon 没有状态属性。
SelectLabel
[data-slot="select-label"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when the select is disabled, by its own prop, a field or a <fieldset>. |
data-readonly | Present when the select is read-only. |
data-required | Present when the select is required. |
SelectTrigger
[data-slot="select-trigger"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the list is closed, including while it animates out. |
data-disabled | Present when the select or the trigger is disabled. |
data-open | Present while the list is open. |
data-placeholder | Present while nothing is selected, so the placeholder shows. |
data-readonly | Present when the select is read-only. |
data-required | Present when the select is required. |
SelectValue
[data-slot="select-value"]
| 属性 | 含义 |
|---|---|
data-placeholder | Present while nothing is selected, so the placeholder shows. |
SelectClear
[data-slot="select-clear"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when the select is disabled or read-only. |
SelectContent
[data-slot="select-content"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the list is closed, including while it animates out. |
data-presentation | popoversheetHow the list presents this time it's open. |
data-open | Present while the list is open. |
data-starting-style | Present for the first frame. Style the state you animate from. |
data-ending-style | Present while the list animates out. Style the state you animate to. |
data-side | toprightbottomleftWhere the list ended up, after flipping away from edges. |
data-align | startcenterendHow the list lines up with the trigger. |
data-modality | keyboardpointerWhether the keyboard or a pointer is in use, for focus styles. |
data-has-icons | Present while any item inside holds an icon part, so items without one can line up. |
SelectItem
[data-slot="select-item"]
| 属性 | 含义 |
|---|---|
data-selected | Present on selected items, and on the check inside them. |
data-disabled | Present when the item can't be chosen. |
data-highlighted | Present on the item with keyboard focus or under the pointer, or highlighted while focus stays in the search field. |
data-has-icon | Present on an item while it holds an icon part. |
SelectItemText
[data-slot="select-item-text"]
| 属性 | 含义 |
|---|---|
data-matched | Present on an item's text while the search matched part of it, which is marked. |
SelectItemIndicator
[data-slot="select-item-indicator"]
| 属性 | 含义 |
|---|---|
data-selected | Present on selected items, and on the check inside them. |
SelectSelectAll
[data-slot="select-select-all"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when nothing the select-all option covers can be chosen. |
data-unchecked | Present on a select-all option while none of its items is selected. |
data-highlighted | Present on the item with keyboard focus or under the pointer, or highlighted while focus stays in the search field. |
SelectEmpty
[data-slot="select-empty"]
| 属性 | 含义 |
|---|---|
data-loading | Present while results load, with status="loading". |
data-empty | Present while no item matches the search. |
SelectStatus
[data-slot="select-status"]
| 属性 | 含义 |
|---|---|
data-loading | Present while results load, with status="loading". |
SelectArrow
[data-slot="select-arrow"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the list is closed, including while it animates out. |
data-open | Present while the list is open. |
data-side | toprightbottomleftWhere the list ended up, after flipping away from edges. |
data-align | startcenterendHow the list lines up with the trigger. |
data-arrow-clamped | Present on the arrow when it stops short of the middle of the trigger, held back by arrowPadding. |
SelectItemIcon
[data-slot="select-item-icon"]
| 属性 | 含义 |
|---|---|
data-mirror | Present on an icon that flips in right-to-left text, with mirror. |
API 参考
Select
container?DocumentFragment | Element | null- Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
open?boolean- Whether the list is open. Pass it to control it.
defaultOpen?boolean- Whether the list starts open, when uncontrolled.
onOpenChange?((open: boolean, details: ChangeDetails<SelectOpenChangeReason>) => void)- Runs when the list wants to open or close.
details.reasonsays why, anddetails.cancel()stops it. onOpenChangeComplete?((open: boolean) => void)- Runs once the list has finished opening or closing, after any animation.
items?ListData<T>- The items as data. Renders the list for you, and lets the trigger show labels and find items by typing before the list has ever opened.
emptyItems?ListData<T>- Items shown instead of
itemswhile the search field is empty, like recent choices. Groups work, like{ type: "group", label: "Recent", items }. Needsitemsand aSelectInput. query?string- The text in the search field, which filters the list. Pass it to control it. Closing the list empties it.
defaultQuery?string- The search field's text at first, when uncontrolled.
onQueryChange?((query: string, details: TextChangeDetails<SelectQueryChangeReason>) => void)- Runs when the search field's text wants to change: typing, or closing the list, which empties it.
filter?ListFilter<T>- How a
SelectInputnarrows the list:"contains","startsWith", a function of the item and the text, whose numeric result also sorts data items, orfalseto keep every item, for results a server already filtered. status?AsyncOptionsStatus- Whether results are loading or failed, for the status and empty parts. Sets
aria-busyon the list while loading. onLoadMore?(() => void)- Runs when the highlight or scrolling reaches the last item, so the next page can load, like
createAsyncOptions'sloadMore. Not again for the same items, unless the last load failed. announcement?((change: ListAnnouncement) => string | null | undefined)- What screen readers hear after typing pauses in the search field, when no
SelectStatusis rendered. Return null for nothing. placeholder?string- What the value shows while nothing is selected.
itemToValue?((value: T) => string)- The string an item's value submits as and is identified by, for object values. Strings pass through, and objects use their
valueorid. itemToLabel?((value: T) => string)- The text a value shows in the trigger, for values whose item isn't rendered, like async results.
isItemEqualToValue?((itemValue: T, value: T) => boolean)- Whether an item's value is the selected value, for object values that aren't the same object.
onHighlight?((value: T | null, details: ListHighlightDetails) => void)- Runs when the highlight moves, with the item's index among the visible items, so a virtualized list can scroll to it.
loop?boolean- Whether arrow keys wrap from the last item to the first.
virtualFocus?boolean- Keeps focus on the trigger while the list is open, as on a native select: arrow keys, Home, End and typing move the highlight, and the trigger points at the highlighted item with
aria-activedescendant. A search field in the list still takes focus. modal?"pointer" | boolean"pointer": an outside press only closes the list.true: also locks scroll and makes the rest of the page inert.false: outside presses reach what they hit.presentation?PresentationSetting<"popover">- How the list presents.
"sheet"slides it up from the bottom of the screen, where it can be swiped away, and"auto"does that on small touch screens. Decided each time it opens; the server renders"popover"for"auto". disabled?boolean- Disables the select like a native one: it can't be focused or changed, and the value isn't submitted.
readOnly?boolean- Keeps the select focusable and its value submitted, but stops changes.
required?boolean- Blocks form submission until a value is selected, with the browser's own message.
name?string- The name the value submits under. Without one, the select submits nothing.
form?string- The id of a form to belong to, when the select isn't inside that form.
autoComplete?string- A hint for the browser's autofill, like
"country". controller?object- Opens, closes, reads and sets the select from anywhere. Create one with
createSelectController(). dismissible?boolean- Whether Escape, an outside press, focus or the window leaving, Android's back gesture and a sheet's swipe can close it. Triggers, Close parts and the controller always can. Pass
falsewhile it holds unsaved work, and ask inonDismissAttempt. onDismissAttempt?function- Runs when
dismissiblerefused a dismissal made on purpose: Escape, an outside press, back or a swipe. Focus or the window leaving is refused without it. Ask "Discard changes?" here. debug?boolean- Logs every state change with its reason to the console, in development builds.
multiple?boolean- Whether several items can be selected. The value is then a list, and the list stays open as items toggle. Whether several items can be selected.
value?T | T[] | null- The selected value. Pass it to control the select.
nullselects nothing. The selected values. Pass it to control the select. The selected value, or values withmultiple. Pass it to control the select. defaultValue?T | T[] | null- The value selected at first, when uncontrolled. A form reset returns to it. The values selected at first, when uncontrolled. A form reset returns to them. The value or values selected at first, when uncontrolled. A form reset returns to it.
onValueChange?union- Runs when a user, a form reset or a controller wants to change the value.
details.reasonsays why, anddetails.cancel()stops it.
SelectTrigger
Select 之外的触发器还接受 controller。
disabled?boolean- Stops the trigger from opening the list. A native button can't be focused or pressed.
controller?object- Connects a trigger outside the select to the select with this controller.
SelectValue
placeholder?string- What shows while nothing is selected. Overrides the select's
placeholder. maxLabels?number- With
multiple, how many labels show before the rest are counted, as in "Apple, Banana and 2 more", joined the way the page's language joins lists, or in English with the defaultgetMoreLabel. getMoreLabel?((count: number) => string)- The words for the labels past
maxLabels.
SelectContent
side?Side- Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the trigger the list opens on.
align?Align- How the popup lines up with the anchor along that side.
startandendfollow the reading direction. How the list lines up with the trigger along that side. sideOffset?number- Gap between the anchor and the popup, in pixels. Gap between the trigger and the list, in pixels.
alignOffset?number- Shift along the anchor, in pixels. Shift along the trigger, in pixels.
collisionPadding?number- Space to keep from the viewport edges, in pixels.
arrowPadding?number- Space to keep between the arrow and the popup's corners, in pixels.
anchor?string | Anchor | null- Positions the popup against this instead of its trigger: an element, a CSS selector, a point like
{ x, y }, or anything withgetBoundingClientRect(). It's read on every check, so it can move. A controller'sopen({ anchor })wins for that open. container?DocumentFragment | Element | null- Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
alignItemWithTrigger?boolean- Whether the list overlaps the trigger so the selected item sits on it, like a native select on macOS. Falls back to opening below when there isn't room, and for touch.
keepMounted?boolean- Whether the list stays in the page, hidden, while closed. Its content keeps its state between opens.
SelectItem
label?string- The text the trigger shows and typing finds, when the content isn't plain text. Not the accessible name: use
aria-labelfor that. disabled?boolean- Keeps the item from being chosen. The keyboard and the pointer skip it. Sets
data-disabledandaria-disabled. index?number- The item's position among all items, for virtualized lists that render only some. Sets
aria-posinsetandaria-setsize. valueT- What the value becomes when the item is chosen. A string, or any value with
itemToValue.
SelectItemIndicator
keepMounted?boolean- Whether the indicator stays in the page while its item isn't selected, so it can be styled or animated in both states.
SelectItemIcon
mirror?boolean- Flips the icon horizontally in right-to-left text, for icons that point a way, like arrows and chevrons. Icons that picture a thing, like a clock or a check, stay as they are.
SelectValueIcon 没有自己的 props,也不接受 children。
SelectClear
keepMounted?boolean- Whether the clear button stays in the page while nothing is selected.
SelectInput、SelectEmpty、SelectStatus、SelectItemText 和 SelectSelectAll
它们都没有自己的 props。SelectInput 开启搜索,SelectItemText 在选项文本中标记搜索匹配的内容,SelectSelectAll 作用于它所在分组的选项,不在分组里时作用于每个选项。没有 SelectStatus 时,输入暂停后,结果数量会通过页面共享的实时区域(live region)播报给屏幕阅读器。announcement 接收 { type: "results", count, query, loading } 并返回播报的措辞,返回 null 则不播报。默认是英文:“3 results”、“No results”或“Loading”。
以数据形式提供的选项
items 里的每一项。分组是 { type: "group", label, items },分隔符是 { type: "separator" }。
valueT- Identifies the item, and is what choosing it reports. A string, or any value with
itemToValue. labelstring- The text shown and matched by typeahead and filtering. A select's trigger shows it once chosen.
keywords?string[]- More words filtering matches, like
["team"]for a plan called Pro. disabled?boolean- Keeps the item from being chosen. The keyboard skips it, like in a native select.
状态
每个部件的渲染函数、基于状态的类名和槽位会收到什么。
SelectTrigger:
openboolean- Whether the list is open.
disabledboolean- Whether the select is disabled, by itself or by a
<fieldset>. readOnlyboolean- Whether the select keeps its value but refuses changes, from its
readOnlyoption. Setsaria-readonly. requiredboolean- Whether a value must be selected before the form submits, from its
requiredoption. Setsaria-required. placeholderboolean- Whether nothing is selected, so the placeholder shows.
SelectValue:
valueunknown- The selected value: one,
null, or a list withmultiple. labelstring- The selected item's label, the labels joined with commas for several, or with
maxLabels, as a list in the page's language, like "Apple, Banana and 2 more". An empty string for none. labelsstring[]- Each selected item's label, in the order they were selected.
placeholderboolean- Whether nothing is selected, so the placeholder shows.
SelectContent 和 SelectList:
openboolean- Whether the list is open. False while it animates out.
presentation"popover" | "sheet"- How it presents this time it's open.
multipleboolean | undefined- Whether several items can be selected.
itemsListData<unknown>- The data items that match the search, for rendering a virtualized list yourself.
statusAsyncOptionsStatus- Whether results are loading or failed.
SelectItem:
highlightedboolean- Whether the item has keyboard focus or is under the pointer.
selectedboolean- Whether its value is in the select's value, compared with
isItemEqualToValuewhen you pass one. disabledboolean- Whether the item's own
disabledprop is set. It can't be highlighted or chosen.
SelectItemIndicator:
selectedboolean- Whether its item is selected. While false, the indicator isn't shown unless
keepMountedis set.
SelectItemIcon:
mirrorboolean- Whether it flips in right-to-left text.
SelectClear:
disabledboolean- Whether the select is disabled or read-only, so there's nothing it can clear.
SelectArrow:
openboolean- Whether the list is open.
SelectInput:
openboolean- Whether the list is open.
disabledboolean- Whether the select is disabled, by itself or by a
<fieldset>. A read-only select's search field stays enabled.
SelectItemText:
segmentsMatchSegment[]- The text in pieces, each marked when it matched. Joined, they're the whole text.
matchedboolean- Whether any piece matched.
SelectSelectAll:
checkedboolean- Whether every item it covers is selected.
indeterminateboolean- Whether some of its items are selected, but not all.
highlightedboolean- Whether it's highlighted, by the keyboard or the pointer.
disabledboolean- Whether it can't be used: nothing it covers can be chosen, or choosing them all would pass
maxSelected.
SelectEmpty:
loadingboolean- Whether results are loading.
emptyboolean- Whether no item matches.
querystring- The text the list is filtered by.
SelectStatus:
status"idle" | "loading" | "error"- Whether results are loading or failed.
loadingboolean- Whether results are loading.
countnumber- How many items are visible.
原因
details.reason 说明值为什么变化:
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
list-navigationKeyboardEvent- Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
clear-pressMouseEvent | KeyboardEvent- A Clear part was pressed, like on an input, a select or a combobox.
resetnone- A form reset.
restorenone- The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone- A controller or
apicall.
以及列表为什么打开或关闭:
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
imperativenone- A controller or
apicall. trigger-pressMouseEvent | KeyboardEvent | TouchEvent- Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its
touchend. outside-pressMouseEvent- A press outside the layer.
escape-keyKeyboardEvent- Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
close-pressMouseEvent | KeyboardEvent | SubmitEvent- A Close part was pressed, or a form with
method="dialog"was submitted. focus-outKeyboardEvent | FocusEvent- Focus left the layer, or Tab moved it out.
window-blurFocusEvent- The window lost focus.
backEvent- Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent- A swipe gesture: a finger, mouse or pen dragged it.
anchor-hiddennone- The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.
dismissible 为 false 时,onDismissAttempt 报告的、被拒绝的关闭:
outside-pressMouseEvent- A press outside the layer.
escape-keyKeyboardEvent- Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
backEvent- Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent- A swipe gesture: a finger, mouse or pen dragged it.
以及搜索文本为什么变化:
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
imperativenone- A controller or
apicall. trigger-pressMouseEvent | KeyboardEvent | TouchEvent- Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its
touchend. outside-pressMouseEvent- A press outside the layer.
escape-keyKeyboardEvent- Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
close-pressMouseEvent | KeyboardEvent | SubmitEvent- A Close part was pressed, or a form with
method="dialog"was submitted. focus-outKeyboardEvent | FocusEvent- Focus left the layer, or Tab moved it out.
window-blurFocusEvent- The window lost focus.
backEvent- Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent- A swipe gesture: a finger, mouse or pen dragged it.
input-changeEvent- Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
控制器
用 createSelectController<Value, Multiple>() 创建一个,并作为 controller 传给 Select 以及它之外的触发器。
每个写入方法都接受一个可选的 { reason, event },传给变更回调。
isOpen()() => boolean- Whether the list is open.
setOpen(open, options?)(open: boolean, options?: SelectChangeOptions<SelectOpenChangeReason> | undefined) => boolean- Opens or closes the list. Returns false when the change was canceled or it was already open or closed.
open(options?)(options?: (SelectChangeOptions<SelectOpenChangeReason> & { signal?: AbortSignal | undefined; }) | undefined) => Promise<...>- Opens the list, and resolves once it closes, with why and how. Resolves exactly once and never rejects: on the next close from any source, when
signalaborts, or with reason"unmount"when the select leaves the page. close(options?)(options?: SelectChangeOptions<SelectOpenChangeReason> | undefined) => boolean- Closes the list. Returns false when the close was canceled or it was already closed.
toggle(options?)(options?: SelectChangeOptions<SelectOpenChangeReason> | undefined) => boolean- Opens the list when it's closed, and closes it when it's open. Returns false when the change was canceled.
getValue()() => SelectValue<T, Multiple>- The selected value.
setValue(value, options?)(value: SelectValue<T, Multiple>, options?: SelectChangeOptions<SelectValueChangeReason> | undefined) => boolean- Selects a value, as a user would. A disabled or read-only select ignores it. Returns false when the change was canceled, ignored or the value was already selected.
clear(options?)(options?: SelectChangeOptions<SelectValueChangeReason> | undefined) => boolean- Selects nothing:
null, or an empty list withmultiple. Returns false when nothing changed. getQuery()() => string- The text in the search field.
setQuery(query, options?)(query: string, options?: SelectChangeOptions<SelectQueryChangeReason> | undefined) => boolean- Changes the text in the search field, which filters the list. Returns false when nothing changed.
focus()() => void- Moves focus to the trigger.
事件
回调先收到新状态,然后收到详情。
| 属性 | 所属 | 收到 |
|---|---|---|
onValueChange | Select | (value, details):新值,以及原因 |
onOpenChange | Select | (open, details):新状态,以及原因 |
onOpenChangeComplete | Select | (open),在动画之后 |
onHighlight | Select | (value, { index, event }):高亮的选项及其行 |
onQueryChange | Select | (query, details):搜索文本、原因,以及是否仍在 composing |
onLoadMore | Select | (),在到达最后一个选项时 |
onDismissAttempt | Select | ({ reason, event }),在关闭被拒绝时 |
无障碍
Select 遵循 WAI-ARIA 只选组合框模式。触发器带有 combobox 角色,浮层是一个 listbox。如果不需要可见的标签,改为给 SelectTrigger 一个 aria-label。
键盘
方向键在打开的列表中移动;Home 和 End 到达第一个和最后一个选项。设置 loop={false} 让方向键在两端停住。浮层跟随触发器继承的文本方向;在从右到左的布局中,用逻辑 CSS 属性设置间距。
设置 virtualFocus,让列表打开期间焦点留在触发器上,就像原生 select 那样:方向键、Home、End 和输入会移动高亮,触发器用 aria-activedescendant 指向它,Tab 关闭列表并继续前进。列表里的搜索字段仍然会获得焦点。
经过测试的行为
下面每一行都是一个自动化测试。
- With alignItemWithTrigger, the selected item sits over the trigger.
- A controller opens the list.
- Is a combobox named by its label that shows the placeholder.
- Click opens the list.
- Enter opens the list and focuses the first item.
- Space opens the list and focuses the first item.
- ArrowDown opens the list and focuses the first item.
- Points to the list it controls while open.
- A click on the open trigger closes the list.
- A click on a trigger in a shadow root opens the list, and it stays open. 仅在 Vue 和 web components 运行。
- Arrow keys move focus through the items.
- Home and End move to the first and last items.
- Arrow keys skip disabled items.
- Typing focuses the next item that starts with the text.
- Enter chooses the focused item, closes and returns focus to the trigger.
- Space chooses the focused item.
- Escape closes without choosing and returns focus to the trigger.
- An ancestor hears Escape already handled.
- The chosen item is selected when the list opens again, and takes focus.
- Selects the next item that starts with the text, like a native select.
- Skips disabled items.
- Clicking an item chooses it and closes the list.
- Clicking a disabled item does nothing.
- Moving over a disabled item leaves the highlight where it was.
- Clicking outside closes without choosing.
- Pressing, dragging to an item and releasing chooses it.
- Enter opens the list after a drag chose an item.
- Enter opens the list after pressing the open trigger and releasing elsewhere.
- A disabled value stays in the trigger, and the list opens on the first enabled item.
- A default value shows its label and is selected.
- Opening with a selected item focuses it.
- Canceling the change keeps the value.
- The list allows several selections.
- Choosing toggles items and keeps the list open.
- Items sit in groups named by their labels.
- Arrow keys move across groups.
- The form submits the value under the select's name.
- Enter in the form's one text field submits it, with no submit button.
- A required select blocks submission until a value is chosen.
- A disabled select can't be opened.
- A read-only select doesn't change its value.
- A disabled fieldset disables the select and leaves it out of the form.
- The list opens below the trigger, at least as wide.
运行于 React、Vue 和 web components。
其他行为:
- A data select whose content part is wrapped in a component renders one list.
- The list is named by the select's label.
- A clear button selects nothing and keeps focus on the select.
- Alt+ArrowUp chooses the focused item and closes, as the APG asks.
- The content says whether the keyboard or a pointer is in use, for styling the highlight.
- A form reset returns the select to its default value.
- Typing on the closed trigger selects items before the list has ever been in the page.
- With virtualFocus, keys move the highlight while focus stays on the trigger, which points at it.
- With virtualFocus, Tab closes the list and moves on from the trigger.
- With virtualFocus, a click on an item chooses it and keeps focus on the trigger.
运行于 React、Vue 和 web components。
带列表内搜索字段的搜索:
- Opening focuses the search field and highlights the selected item.
- The search field is a combobox that controls the listbox in the list.
- Typing filters the list and highlights the first match.
- A field whose onChange renders the filtered list at once still highlights the first match. 仅在 React 运行。
- Typing never jumps by first letter: the characters go into the field.
- Arrow keys move the highlight while focus stays in the field.
- Home and End are the field's, so the highlight stays.
- Enter chooses the highlighted item, closes, and focus returns to the trigger.
- A click on an item chooses it.
- Escape closes the list and focus returns to the trigger.
- The search empties once the list closes.
- An empty message shows when nothing matches.
- Matches ignore case and accents.
- Labels mark what the search matched.
- With multiple, choosing keeps the list open and focus in the field.
- Tab closes the list and moves on from the trigger.
- No axe violations while searching.
- Typing on the closed trigger still selects by first letter.
- Recent items show until the user types, then the results.
- A recent item is chosen like any other, and its label shows in the trigger.
运行于 React、Vue 和 web components。
在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器记录:
- Announcements while choosing with a keyboard.
运行于 React、Vue 和 web components。