组件Controls
Select
@mox-hub/ui 组件 · Controls · canonical
select@mox-hub/uiControlscanonicalsrc/components/select.tsx变体演示select
Props API
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
| children | React.ReactNode | — | — |
| inputRef | React.Ref<HTMLInputElement> | — | A ref to access the hidden input element. |
| name | string | — | Identifies the field when a form is submitted. |
| form | string | — | Identifies the form that owns the hidden input. |
| autoComplete | string | — | Provides a hint to the browser for autofill. |
| id | string | — | The id of the Select. |
| required | boolean | — | Whether the user must choose a value before submitting a form. |
| readOnly | boolean | — | Whether the user should be unable to choose a different option from the select popup. |
| disabled | boolean | — | Whether the component should ignore user interaction. |
| multiple | Multiple | — | Whether multiple items can be selected. |
| highlightItemOnHover | boolean | — | Whether moving the pointer over items should highlight them. |
| defaultOpen | boolean | — | Whether the select popup is initially open. |
| onOpenChange | (open: boolean, eventDetails: SelectRootOpenChangeEventDetails) => void | — | Event handler called when the select popup is opened or closed. |
| onOpenChangeComplete | (open: boolean) => void | — | Event handler called after any animations complete when the select popup is opened or closed. |
| open | boolean | — | Whether the select popup is currently open. |
| modal | boolean | — | Determines if the select enters a modal state when open. |
| actionsRef | React.RefObject<SelectRootActions> | — | A ref to imperative actions. |
| items | readonly Group<any>[] | Record<string, React.ReactNode> | readonly { label: React.ReactNode; value: any; }[] | — | Data structure of the items rendered in the select popup. |
| itemToStringLabel | (itemValue: Value) => string | — | When the item values are objects (`<Select.Item value={object}>`), this function converts the object value to a string representation for display in the trigger. |
| itemToStringValue | (itemValue: Value) => string | — | When the item values are objects (`<Select.Item value={object}>`), this function converts the object value to a string representation for form submission. |
| isItemEqualToValue | (itemValue: Value, value: Value) => boolean | — | Custom comparison logic used to determine if a select item value matches the current selected value. Useful when item values are objects without matching referentially. |
| defaultValue | SelectInputValue<Value, Multiple> | — | The uncontrolled value of the select when it's initially rendered. |
| value | SelectInputValue<Value, Multiple> | — | The value of the select. Use when controlled. |
| onValueChange | (value: SelectOutputValue<Value, Multiple> | (Multiple extends true ? never : null), eventDetails: SelectRootChangeEventDetails) => void | — | Event handler called when the value of the select changes. |
源码
import * as React from "react"
import { Select as SelectPrimitive } from "@base-ui/react/select"
import { cn } from "../lib/utils"
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
import {
SURFACE_POPOVER_CLASS,
menuItemVariants,
menuLabelVariants,
} from "./menu-styles"
const Select = SelectPrimitive.Root
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
return (
<SelectPrimitive.Group
data-slot="select-group"
className={cn("scroll-my-1", className)}
{...props}
/>
)
}
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
return (
<SelectPrimitive.Value
data-slot="select-value"
className={cn("flex flex-1 text-start", className)}
{...props}
/>
)
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: SelectPrimitive.Trigger.Props & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-1.5 rounded-md border border-input bg-transparent py-2 pe-2 ps-2.5 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] duration-fast outline-none focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-control-md data-[size=sm]:h-control-sm *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon
render={
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
}
/>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
side = "bottom",
sideOffset = 4,
align = "center",
alignOffset = 0,
alignItemWithTrigger = true,
...props
}: SelectPrimitive.Popup.Props &
Pick<
SelectPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger"
>) {
// base-ui 在渲染 List 时把 Popup 降为 presentation,listbox 角色落在 List 上;
// 无障碍名必须同时挂到 List,否则 getByRole('listbox', { name }) 与读屏都拿不到名字。
const {
"aria-label": listLabel,
"aria-labelledby": listLabelledBy,
...popupProps
} = props;
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Positioner
side={side}
sideOffset={sideOffset}
align={align}
alignOffset={alignOffset}
alignItemWithTrigger={alignItemWithTrigger}
className="isolate z-modal"
>
<SelectPrimitive.Popup
data-slot="select-content"
data-align-trigger={alignItemWithTrigger}
className={cn("relative isolate z-modal max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto overscroll-contain duration-fast data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", SURFACE_POPOVER_CLASS, className )}
{...popupProps}
aria-label={listLabel}
aria-labelledby={listLabelledBy}
>
<SelectScrollUpButton />
<SelectPrimitive.List
data-slot="select-list"
className="p-1"
aria-label={listLabel}
aria-labelledby={listLabelledBy}
>
{children}
</SelectPrimitive.List>
<SelectScrollDownButton />
</SelectPrimitive.Popup>
</SelectPrimitive.Positioner>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: SelectPrimitive.GroupLabel.Props) {
return (
<SelectPrimitive.GroupLabel
data-slot="select-label"
className={cn(menuLabelVariants(), className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: SelectPrimitive.Item.Props) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
menuItemVariants(),
"pe-8 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<SelectPrimitive.ItemText className="flex min-w-0 flex-1 gap-2 truncate whitespace-nowrap">
{children}
</SelectPrimitive.ItemText>
<SelectPrimitive.ItemIndicator
render={
<span className="pointer-events-none absolute end-2 flex size-4 items-center justify-center" />
}
>
<CheckIcon className="pointer-events-none" />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: SelectPrimitive.Separator.Props) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpArrow>) {
return (
<SelectPrimitive.ScrollUpArrow
data-slot="select-scroll-up-button"
className={cn(
"top-0 z-sticky flex w-full cursor-default items-center justify-center bg-(--surface-popover-bg) py-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<ChevronUpIcon
/>
</SelectPrimitive.ScrollUpArrow>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownArrow>) {
return (
<SelectPrimitive.ScrollDownArrow
data-slot="select-scroll-down-button"
className={cn(
"bottom-0 z-sticky flex w-full cursor-default items-center justify-center bg-(--surface-popover-bg) py-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<ChevronDownIcon
/>
</SelectPrimitive.ScrollDownArrow>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}
可访问性与 RTL
- 键盘:交互件保留
:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。 - RTL:间距、对齐与方向性图标使用逻辑属性 (
ms-*/text-start/rtl:-scale-x-100);通过ThemeProvider或I18nProvider的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。 - 文案:优先用组件
labels/translate/translatorprops,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。 - 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。
用法说明
下拉选择,由 Select、Trigger、Value、Content、Item 组合;大量选项或需要搜索时用 combobox。