> Leaf UI 0.17.3 · Package: @ifhover/leaf-ui · Source: c3221834f84f2f48481a2054026b713456f8e5dc
> Browser documentation: https://ifhover.github.io/leaf-ui/components/select.html

> For AI agents: the complete documentation index is available at https://ifhover.github.io/leaf-ui/llms.txt, the full documentation bundle is available at https://ifhover.github.io/leaf-ui/llms-full.txt.

# Select 选择器

从平铺选项中选择一项或多项；层级选项使用 [TreeSelect](https://ifhover.github.io/leaf-ui/components/tree-select.md)。


## 基础用法

[](#)
选项的 `value` 使用唯一的非空字符串。为控件提供关联标签或 `aria-label`。


basic.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/basic.tsx"
import { Select } from '@ifhover/leaf-ui';

const options = [
  { value: 'design', label: '设计工作室' },
  { value: 'product', label: '产品团队' },
  { value: 'engineering', label: '工程团队' },
  { value: 'archived', label: '归档项目', disabled: true },
];

export function SelectBasic() {
  return <Select aria-label="选择团队" options={options} placeholder="请选择团队" />;
}
```

展开代码


## 示例

### 受控与校验

[](#)
通过 `value` 和 `onChange` 管理选择结果。单选清除时回调返回 `""` 和 `undefined`；受控字段响应表单重置时，也需要重置应用状态。


项目可见性

提交

controlled.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/controlled.tsx"
import { Button, Form, FormField, Select, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function SelectControlled() {
  const [value, setValue] = useState('');
  const [submitted, setSubmitted] = useState(false);
  const error = submitted && !value;
  return (
    <Form
      layout="vertical"
      noValidate
      onSubmit={(event) => {
        event.preventDefault();
        setSubmitted(true);
      }}
    >
      <FormField label="项目可见性" error={error ? '请选择可见性' : undefined}>
        <Select
          name="visibility"
          value={value}
          onChange={setValue}
          allowClear
          status={error ? 'error' : undefined}
          placeholder="请选择"
          options={[
            { value: 'public', label: '公开' },
            { value: 'team', label: '团队' },
            { value: 'private', label: '私密' },
          ]}
        />
      </FormField>
      <Button type="submit">提交</Button>
      {submitted && value && <Text role="status">已提交：{value}</Text>}
    </Form>
  );
}
```

展开代码

### 控件尺寸

通过 `size` 设置控件尺寸。


sm查询

md查询

lg查询

control-sizes.tsx

复制代码

```tsx lineNumbers file="../../src/examples/guide/control-sizes.tsx"
import type { ControlSize } from '@ifhover/leaf-ui';
import { Button, Flex, Input, Select, Text } from '@ifhover/leaf-ui';

export function ControlSizes() {
  return (
    <Flex direction="column" gap="md">
      {(['sm', 'md', 'lg'] as const).map((size: ControlSize) => (
        <Flex key={size} align="center" gap="sm" wrap>
          <Text tone="muted">{size}</Text>
          <Input
            style={{ flex: '1 1 120px', width: 0 }}
            size={size}
            aria-label={`${size} 搜索`}
            placeholder="搜索项目"
          />
          <Select
            style={{ flex: '1 1 120px', width: 0 }}
            size={size}
            aria-label={`${size} 状态`}
            defaultValue="all"
            options={[
              { label: '全部状态', value: 'all' },
              { label: '进行中', value: 'active' },
            ]}
          />
          <Button size={size}>查询</Button>
        </Flex>
      ))}
    </Flex>
  );
}
```

展开代码

### 搜索

`showSearch` 开启本地筛选。`label` 是 React 节点时，使用 `searchLabel` 提供搜索文字；远程筛选可设置 `filterOption={false}`，再通过 `onSearch` 更新选项。


search.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/search.tsx"
import { Select } from '@ifhover/leaf-ui';

const options = [
  { value: 'design', label: '设计工作室' },
  { value: 'product', label: '产品团队' },
  { value: 'engineering', label: '工程团队' },
  { value: 'archived', label: '归档项目', disabled: true },
];

export function SelectSearch() {
  return (
    <Select
      aria-label="搜索团队"
      showSearch
      allowClear
      options={options}
      placeholder="输入团队名称搜索"
    />
  );
}
```

展开代码

### 多选

多选使用字符串数组，清除返回 `[]`。设置 `name` 后，原生表单在同一字段名下提交多个值，使用 `formData.getAll(name)` 读取。搜索文字为空时，Backspace 可移除最后一个未禁用标签。


设计工作室

当前值：design

multiple.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/multiple.tsx"
import { Flex, Select, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

const options = [
  { value: 'design', label: '设计工作室' },
  { value: 'product', label: '产品团队' },
  { value: 'engineering', label: '工程团队' },
  { value: 'archived', label: '归档项目', disabled: true },
];

export function SelectMultiple() {
  const [value, setValue] = useState<string[]>(['design']);
  return (
    <Flex direction="column" gap="sm">
      <Select
        aria-label="选择多个团队"
        multiple
        allowClear
        options={options}
        value={value}
        onChange={setValue}
        placeholder="请选择团队"
      />
      <Text tone="muted" role="status">
        当前值：{value.join(', ') || '未选择'}
      </Text>
    </Flex>
  );
}
```

展开代码

### 状态

`loading` 用于选项请求中的状态；没有可选项时，可以通过 `notFoundContent` 提供提示。


禁用

加载中

空选项

states.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/states.tsx"
import { Flex, Select, Text } from '@ifhover/leaf-ui';

const options = [
  { value: 'design', label: '设计工作室' },
  { value: 'product', label: '产品团队' },
  { value: 'engineering', label: '工程团队' },
  { value: 'archived', label: '归档项目', disabled: true },
];

export function SelectStates() {
  return (
    <Flex direction="column" gap="md">
      <Flex direction="column" gap="sm">
        <Text tone="muted">禁用</Text>
        <Select aria-label="禁用的团队选择" options={options} defaultValue="design" disabled />
      </Flex>
      <Flex direction="column" gap="sm">
        <Text tone="muted">加载中</Text>
        <Select aria-label="正在加载的团队" options={[]} loading placeholder="加载中" />
      </Flex>
      <Flex direction="column" gap="sm">
        <Text tone="muted">空选项</Text>
        <Select
          aria-label="暂无可选团队"
          options={[]}
          notFoundContent="还没有团队"
          placeholder="暂无团队"
        />
      </Flex>
    </Flex>
  );
}
```

展开代码

### 分组选项

分组标题用于组织选项，不能被选择。组内选项照常参与搜索。


grouped-options.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/grouped-options.tsx"
import { Select, type SelectOptionGroup } from '@ifhover/leaf-ui';

const options: SelectOptionGroup[] = [
  {
    label: '设计',
    options: [
      { value: 'ui', label: '界面设计' },
      { value: 'ux', label: '体验设计' },
    ],
  },
  {
    label: '工程',
    options: [{ value: 'web', label: '前端开发' }],
  },
];

export function GroupedOptions() {
  return <Select aria-label="专业方向" options={options} placeholder="选择专业方向" />;
}
```

展开代码

### 限制选择数量

`maxCount` 限制可选数量，达到上限后仍可取消已选项。


设计工作室产品团队

limits.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/limits.tsx"
import { Select } from '@ifhover/leaf-ui';

const options = [
  { value: 'design', label: '设计工作室' },
  { value: 'product', label: '产品团队' },
  { value: 'engineering', label: '工程团队' },
  { value: 'archived', label: '归档项目', disabled: true },
];

export function SelectLimits() {
  return (
    <Select
      aria-label="最多选择两个团队"
      multiple
      options={options}
      defaultValue={['design', 'product']}
      maxCount={2}
      allowClear
      placeholder="最多选择两个团队"
    />
  );
}
```

展开代码

### 标签换行

默认允许标签换行。设置 `tagWrap={false}` 后，放不下的标签合并为 `+N`；`maxTagCount` 只限制显示数量，不限制实际选择。`maxTagCount="responsive"` 同样按可用宽度单行折叠。


默认换行

一个名称比较长的产品设计团队前端开发服务端开发日常运营

单行显示

一个名称比较长的产品设计团队前端开发服务端开发日常运营+4

single-line.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/single-line.tsx"
import { Flex, Select, Text } from '@ifhover/leaf-ui';

const options = [
  { value: 'design', label: '一个名称比较长的产品设计团队' },
  { value: 'web', label: '前端开发' },
  { value: 'server', label: '服务端开发' },
  { value: 'operations', label: '日常运营' },
];

const selected = options.map((option) => option.value);

export function SingleLine() {
  return (
    <Flex direction="column" gap="md">
      <Flex direction="column" gap="sm">
        <Text tone="muted">默认换行</Text>
        <Select
          aria-label="允许换行的团队标签"
          multiple
          options={options}
          defaultValue={selected}
        />
      </Flex>
      <Flex direction="column" gap="sm">
        <Text tone="muted">单行显示</Text>
        <Select
          aria-label="单行团队标签"
          multiple
          tagWrap={false}
          options={options}
          defaultValue={selected}
        />
      </Flex>
    </Flex>
  );
}
```

展开代码

### 创建选项

[](#)
设置 `allowCreate` 后，输入内容与已有选项的值或搜索文字不完全相同时，会出现创建候选；选择候选才创建选项。需要在应用中保留新选项时，通过 `onCreate` 更新 `options`。


设计

create-option.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/create-option.tsx"
import { Select, type SelectOption } from '@ifhover/leaf-ui';
import { useState } from 'react';

const initialOptions: SelectOption[] = [
  { value: 'design', label: '设计' },
  { value: 'engineering', label: '工程' },
];

export function CreateOption() {
  const [options, setOptions] = useState(initialOptions);
  const [value, setValue] = useState<string[]>(['design']);
  return (
    <Select
      aria-label="项目标签"
      multiple
      allowCreate
      options={options}
      value={value}
      onChange={setValue}
      onCreate={(option) => setOptions((current) => [...current, option])}
      placeholder="选择或输入新标签"
    />
  );
}
```

展开代码

### 大列表

选项超过 100 个时自动启用虚拟滚动，无需额外设置 `virtual`。需要关闭时传入 `virtual={false}`。


virtual-list.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/virtual-list.tsx"
import { Select } from '@ifhover/leaf-ui';

const options = Array.from({ length: 5000 }, (_, index) => ({
  value: String(index),
  label: `项目 ${index + 1}`,
}));

export function VirtualList() {
  return (
    <Select aria-label="搜索项目" options={options} placeholder="搜索 5000 个选项" showSearch />
  );
}
```

展开代码

### 自定义选项内容

使用 `optionRender` 补充选项内容，选中值仍使用 `label`。


rich-options.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/rich-options.tsx"
import { Select, Space, Text } from '@ifhover/leaf-ui';

const options = [
  { value: 'garden', label: 'Leaf Garden Design System' },
  { value: 'studio', label: 'Leaf Studio' },
  { value: 'notes', label: 'Leaf Notes' },
];

export function SelectRichOptions() {
  return (
    <Select
      aria-label="选择项目"
      options={options}
      placeholder="选择项目"
      optionRender={(option) => (
        <Space direction="vertical" align="stretch" size={0}>
          <Text strong>{option.label}</Text>
          <Text tone="muted">{option.value}</Text>
        </Space>
      )}
    />
  );
}
```

展开代码

### 自定义标签

自定义标签的关闭操作应调用 `tagRender` 提供的 `remove`，由组件处理移除。


设计工作室产品团队

custom-tags.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/custom-tags.tsx"
import { Select, Tag } from '@ifhover/leaf-ui';

const options = [
  { value: 'design', label: '设计工作室' },
  { value: 'product', label: '产品团队' },
  { value: 'engineering', label: '工程团队' },
  { value: 'archived', label: '归档项目', disabled: true },
];

export function CustomTags() {
  return (
    <Select
      aria-label="自定义团队标签"
      multiple
      defaultValue={['design', 'product']}
      options={options}
      placeholder="选择团队"
      tagRender={(option, remove) => (
        <Tag closable onClose={remove}>
          {option.label}
        </Tag>
      )}
    />
  );
}
```

展开代码

### 浮层宽度

浮层默认跟随控件宽度；`popupWidth="auto"` 按内容定宽，数字指定固定像素宽度。需要最大宽度时设置 `popupMaxWidth`，各种模式均受可用视口宽度限制。


跟随控件

按内容定宽，最大 320px

固定 300px

popup.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/popup.tsx"
import { Flex, Select, Text } from '@ifhover/leaf-ui';

const options = [
  { value: 'garden', label: 'Leaf Garden Design System' },
  { value: 'studio', label: 'Leaf Studio' },
  { value: 'notes', label: 'Leaf Notes' },
];

export function SelectPopup() {
  return (
    <Flex direction="column" gap="md">
      <Flex direction="column" gap="sm">
        <Text tone="muted">跟随控件</Text>
        <Select aria-label="跟随控件" options={options} placeholder="选择项目" />
      </Flex>
      <Flex direction="column" gap="sm">
        <Text tone="muted">按内容定宽，最大 320px</Text>
        <Select
          aria-label="按内容定宽，最大 320px"
          popupWidth="auto"
          popupMaxWidth={320}
          options={options}
          placeholder="选择项目"
        />
      </Flex>
      <Flex direction="column" gap="sm">
        <Text tone="muted">固定 300px</Text>
        <Select aria-label="固定 300px" popupWidth={300} options={options} placeholder="选择项目" />
      </Flex>
    </Flex>
  );
}
```

展开代码

### 控制浮层与附加操作

`open` 与 `onOpenChange` 控制展开状态。使用 `popupRender` 追加操作时，保留传入的 `content`，不要替换选项列表。


设计工作室

打开选项

popup-action.tsx

复制代码

```tsx lineNumbers file="../../src/examples/select/popup-action.tsx"
import { Button, Flex, Select } from '@ifhover/leaf-ui';
import { useState } from 'react';

const options = [
  { value: 'design', label: '设计工作室' },
  { value: 'product', label: '产品团队' },
  { value: 'engineering', label: '工程团队' },
  { value: 'archived', label: '归档项目', disabled: true },
];

export function PopupAction() {
  const [open, setOpen] = useState(false);
  return (
    <Flex direction="column" gap="sm">
      <Select
        aria-label="选择团队并完成"
        multiple
        defaultValue={['design']}
        open={open}
        onOpenChange={setOpen}
        options={options}
        placeholder="选择团队"
        popupRender={(content) => (
          <>
            {content}
            <Flex justify="end">
              <Button onClick={() => setOpen(false)} size="sm">
                完成
              </Button>
            </Flex>
          </>
        )}
      />
      <Flex>
        <Button variant="outline" onClick={() => setOpen(true)}>
          打开选项
        </Button>
      </Flex>
    </Flex>
  );
}
```

展开代码


## API

### Select API

Select 的组件参数。

`name`、`required`、`form` 与非受控重置参与[表单](https://ifhover.github.io/leaf-ui/components/form.md)接入；其余原生 input 属性及 `aria-*` 传递给输入框，`className` 与 `style` 作用于外层容器。共享浮层参数见 [PopupOptions](https://ifhover.github.io/leaf-ui/api/popup-options.md)。

| 属性                  | 类型                                                                                                                                                                   | 默认值                  | 说明                                                          |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- | ----------------------------------------------------------- |
| `options`           | `readonly (`[`SelectOption`](#selectoption)`\|`[`SelectOptionGroup`](#selectoptiongroup-api)`)[]`                                                                    | 必填                   | 选项列表                                                        |
| `value`             | `string \| readonly string[]`                                                                                                                                        | —                    | 受控值；省略时使用内部非受控值。                                            |
| `defaultValue`      | `string \| readonly string[]`                                                                                                                                        | `multiple ? [] : ''` | 非受控初始值；单选默认为空字符串，多选默认为空数组，表单重置时恢复。                          |
| `onChange`          | `((value: string, option?: `[`SelectOption`](#selectoption)`) => void) \| ((value: string[], options: `[`SelectOption`](#selectoption)`[]) => void)`                 | —                    | 单选返回值和选项，清除时为 '' 和 undefined；多选返回值数组和选项数组，清除时均为空数组。         |
| `multiple`          | `false \| true`                                                                                                                                                      | `false`              | 多选时值为数组，默认 \[]                                              |
| `size`              | `'sm' \| 'md' \| 'lg'`                                                                                                                                               | `'md'`               | 选择器尺寸                                                       |
| `status`            | `'error' \| 'warning'`                                                                                                                                               | —                    | 校验状态                                                        |
| `disabled`          | `boolean`                                                                                                                                                            | `false`              | 禁用交互。                                                       |
| `allowClear`        | `boolean`                                                                                                                                                            | `false`              | 展示清除按钮                                                      |
| `showSearch`        | `boolean`                                                                                                                                                            | `false`              | 允许输入搜索选项                                                    |
| `filterOption`      | `boolean \| ((query: string, option: `[`SelectOption`](#selectoption)`) => boolean)`                                                                                 | `true`               | 自定义筛选，false 用于外部筛选                                          |
| `onSearch`          | `(query: string) => void`                                                                                                                                            | —                    | 搜索文字变化                                                      |
| `loading`           | `boolean`                                                                                                                                                            | `false`              | 加载提示                                                        |
| `notFoundContent`   | `ReactNode`                                                                                                                                                          | —                    | 没有选项时的内容                                                    |
| `maxCount`          | `number`                                                                                                                                                             | —                    | 多选数量上限，已选项可继续取消                                             |
| `maxTagCount`       | `number \| 'responsive'`                                                                                                                                             | —                    | 最多展示的标签数；responsive 根据可用宽度自动折叠。                             |
| `tagWrap`           | `boolean`                                                                                                                                                            | `true`               | 允许多选标签换行；false 单行显示并自动折叠溢出项。                                |
| `allowCreate`       | `boolean`                                                                                                                                                            | `false`              | 允许选择新建项；查询文字与已有 value 或搜索文字完全相同时不出现新建项，同时启用搜索。              |
| `onCreate`          | `(option: `[`SelectOption`](#selectoption)`) => void`                                                                                                                | —                    | 选择新建项后返回该选项；组件内部保留它，需要持久保存时由应用更新 options。                   |
| `labelRender`       | `(option: `[`SelectOption`](#selectoption)`) => ReactNode`                                                                                                           | —                    | 自定义选中值的展示。                                                  |
| `optionRender`      | `(option: `[`SelectOption`](#selectoption)`) => ReactNode`                                                                                                           | —                    | 自定义选项内容                                                     |
| `tagRender`         | `(option: `[`SelectOption`](#selectoption)`, remove: () => void) => ReactNode`                                                                                       | —                    | 自定义选中标签；通过 remove 请求移除。                                     |
| `open`              | `boolean`                                                                                                                                                            | —                    | 控制面板是否展开。                                                   |
| `defaultOpen`       | `boolean`                                                                                                                                                            | `false`              | 面板初始展开状态。                                                   |
| `onOpenChange`      | `(open: boolean) => void`                                                                                                                                            | —                    | 展开或收起选项面板                                                   |
| `inputReadOnly`     | `boolean`                                                                                                                                                            | —                    | 只禁止手动输入，仍可在面板中选择。                                           |
| `virtual`           | `boolean`                                                                                                                                                            | 选项超过 100 时启用         | 仅渲染可见项目                                                     |
| `listHeight`        | `number`                                                                                                                                                             | `248`                | 列表高度                                                        |
| `optionHeight`      | `number`                                                                                                                                                             | 由主题和密度计算             | 虚拟列表的预估行高；默认由主题和密度计算，实际行会被测量。                               |
| `popupWidth`        | `number \| string`                                                                                                                                                   | `'trigger'`          | 浮层宽度；trigger 与触发控件等宽，auto 按内容定宽（可比控件窄），数字为固定像素值，也支持 CSS 长度。 |
| `popupMaxWidth`     | `number \| string`                                                                                                                                                   | —                    | 可选的浮层最大宽度；未设置时不额外限制，仍受可视区域限制。                               |
| `onPopupScroll`     | `(event: React.UIEvent<HTMLDivElement>) => void`                                                                                                                     | —                    | 浮层滚动事件，可用来加载下一页。                                            |
| `popupPlacement`    | `'top' \| 'top-start' \| 'top-end' \| 'bottom' \| 'bottom-start' \| 'bottom-end' \| 'left' \| 'left-start' \| 'left-end' \| 'right' \| 'right-start' \| 'right-end'` | —                    | 浮层相对触发控件的位置。                                                |
| `popupClassName`    | `string`                                                                                                                                                             | —                    | 浮层样式                                                        |
| `popupStyle`        | `CSSProperties`                                                                                                                                                      | —                    | 浮层样式                                                        |
| `popupRender`       | `(content: ReactNode) => ReactNode`                                                                                                                                  | —                    | 包装或补充面板内容，保留传入的内容以维持交互。                                     |
| `getPopupContainer` | `() => Element \| DocumentFragment`                                                                                                                                  | —                    | 返回浮层的挂载容器，也可返回 ShadowRoot。                                  |
| `name`              | `string`                                                                                                                                                             | —                    | 原生 FormData 中的字段名。                                          |
| `form`              | `string`                                                                                                                                                             | —                    | 关联的原生表单 ID。                                                 |
| `required`          | `boolean`                                                                                                                                                            | `false`              | 要求整体值非空，复合控件只校验一次。                                          |
| `ref`               | `Ref<HTMLInputElement>`                                                                                                                                              | —                    | 输入框引用                                                       |

### SelectOption

通过 options 传入的选项；value 用于标识选项。

| 属性            | 类型          | 默认值     | 说明                                    |
| ------------- | ----------- | ------- | ------------------------------------- |
| `value`       | `string`    | 必填      | 唯一选项值；不能使用空字符串。                       |
| `label`       | `ReactNode` | 必填      | 选项内容，可以是文字或 React 节点。                 |
| `disabled`    | `boolean`   | `false` | 禁用该选项。                                |
| `searchLabel` | `string`    | —       | 搜索纯文本；省略时使用字符串或数字 label，其他内容使用 value。 |

### SelectOptionGroup API

包含分组标题和选项列表的选项分组。

| 属性        | 类型                                             | 默认值 | 说明       |
| --------- | ---------------------------------------------- | --- | -------- |
| `label`   | `ReactNode`                                    | 必填  | 展示文字或内容。 |
| `options` | `readonly `[`SelectOption`](#selectoption)`[]` | 必填  | 可供选择的选项。 |
