106k
New

选择框

显示一个选项列表供用户选择——通过按钮触发。

import {
  Select,
  SelectContent,

安装

pnpm dlx shadcn@latest add select

用法

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
<Select>
  <SelectTrigger className="w-[180px]">
    <SelectValue placeholder="主题" />
  </SelectTrigger>
  <SelectContent>
    <SelectItem value="light">浅色</SelectItem>
    <SelectItem value="dark">深色</SelectItem>
    <SelectItem value="system">系统</SelectItem>
  </SelectContent>
</Select>

示例

项目与触发器对齐

SelectContent 上使用 position 属性来控制对齐方式。当 position="item-aligned"(默认)时,弹出层定位使选中项出现在触发器上方。当 position="popper" 时,弹出层与触发器边缘对齐。

Toggle to align the item with the trigger.

"use client"

import * as React from "react"

分组

使用 SelectGroupSelectLabelSelectSeparator 来组织项目。

import {
  Select,
  SelectContent,

可滚动

一个拥有大量项目且可以滚动的选择框。

import {
  Select,
  SelectContent,

禁用状态

import {
  Select,
  SelectContent,

无效状态

Field 组件上添加 data-invalid 属性,并在 SelectTrigger 组件上添加 aria-invalid 属性以展示错误状态。

<Field data-invalid>
  <FieldLabel>水果</FieldLabel>
  <SelectTrigger aria-invalid>
    <SelectValue />
  </SelectTrigger>
</Field>
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import {
  Select,

API 参考

请参阅 Radix UI Select 文档。