> Leaf UI 0.17.3 · Package: @ifhover/leaf-ui · Source: c3221834f84f2f48481a2054026b713456f8e5dc
> Browser documentation: https://ifhover.github.io/leaf-ui/components/auto-complete.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.

# AutoComplete 自动完成

在允许自由填写的同时提供输入建议。


## 基础用法

建议默认进行不区分大小写的包含匹配，仍允许自由填写。`onChange` 响应输入和选择，`onSelect` 只响应选择建议。带 `disabled` 的建议不可选中。


项目名称

输入：空最近选中：无

basic.tsx

复制代码

```tsx lineNumbers file="../../src/examples/auto-complete/basic.tsx"
import { AutoComplete, Flex, Form, FormField, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

const options = [
  { value: 'Leaf Garden' },
  { value: 'Leaf Studio' },
  { value: 'Pine Forest' },
  { value: 'Archived Garden', disabled: true },
];

export function AutoCompleteBasic() {
  const [value, setValue] = useState('');
  const [selected, setSelected] = useState('');

  return (
    <Form layout="vertical">
      <FormField label="项目名称">
        <AutoComplete
          aria-label="项目名称"
          options={options}
          placeholder="输入 Leaf 或自由填写"
          value={value}
          onChange={setValue}
          onSelect={setSelected}
        />
      </FormField>
      <Flex direction="column" gap={8} role="status">
        <Text tone="muted">输入：{value || '空'}</Text>
        <Text tone="muted">最近选中：{selected || '无'}</Text>
      </Flex>
    </Form>
  );
}
```

展开代码

聚焦或输入时展开建议。方向键高亮可用项，Enter 选择，Escape 收起，Tab 继续访问后续控件；输入法合成期间的 Enter 不会选中建议。


## 示例

### 动态建议

`onSearch` 接收输入文本，清除时收到空字符串，选择建议时不触发。建议由应用生成或从服务端获取时，设置 `filterOption={false}` 可直接展示结果，不再进行本地过滤。


邮箱地址

search.tsx

复制代码

```tsx lineNumbers file="../../src/examples/auto-complete/search.tsx"
import { AutoComplete, type AutoCompleteOption, Form, FormField } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function AutoCompleteSearch() {
  const [options, setOptions] = useState<AutoCompleteOption[]>([]);

  return (
    <Form layout="vertical">
      <FormField label="邮箱地址">
        <AutoComplete
          aria-label="邮箱地址"
          placeholder="输入邮箱前缀"
          options={options}
          allowClear
          filterOption={false}
          onSearch={(query) => {
            const prefix = query.split('@')[0] ?? '';
            setOptions(
              prefix
                ? ['gmail.com', 'outlook.com', 'icloud.com'].map((domain) => ({
                    value: `${prefix}@${domain}`,
                  }))
                : [],
            );
          }}
        />
      </FormField>
    </Form>
  );
}
```

展开代码

### 分组建议

通过分组标题和对应的 `options` 组织建议。富文本名称使用 `searchLabel` 提供搜索文字；选择后写入输入框的是 `value`，不是 `label`。


团队邮箱

capabilities.tsx

复制代码

```tsx lineNumbers file="../../src/examples/auto-complete/capabilities.tsx"
import { AutoComplete, Flex, Form, FormField, Text } from '@ifhover/leaf-ui';

const options = [
  {
    label: '团队',
    options: [
      {
        value: 'alice@example.com',
        label: (
          <Flex gap={8} align="center">
            <Text strong>Alice</Text>
            <Text tone="muted">设计</Text>
          </Flex>
        ),
        searchLabel: 'Alice 设计',
      },
      {
        value: 'bob@example.com',
        label: (
          <Flex gap={8} align="center">
            <Text strong>Bob</Text>
            <Text tone="muted">工程</Text>
          </Flex>
        ),
        searchLabel: 'Bob 工程',
      },
    ],
  },
];

export function Capabilities() {
  return (
    <Form layout="vertical">
      <FormField label="团队邮箱">
        <AutoComplete aria-label="团队邮箱" options={options} placeholder="搜索姓名或职责" />
      </FormField>
    </Form>
  );
}
```

展开代码

### 加载与重试

本例模拟一次加载失败，重试会异步加载本地建议并替换错误内容。实际远程请求的防抖与响应顺序由应用处理。受控 `open` 需要在 `onOpenChange` 中更新。


远程项目

加载失败

模拟失败

loading.tsx

复制代码

```tsx lineNumbers file="../../src/examples/auto-complete/loading.tsx"
import { AutoComplete, type AutoCompleteOption, Button, Flex, Form, FormField, Text } from '@ifhover/leaf-ui';
import { useRef, useState } from 'react';

export function AutoCompleteLoading() {
  const [state, setState] = useState<'loading' | 'error' | 'ready'>('error');
  const [options, setOptions] = useState<AutoCompleteOption[]>([]);
  const [open, setOpen] = useState(false);
  const input = useRef<HTMLInputElement>(null);

  const retry = async () => {
    setState('loading');
    setOpen(true);
    input.current?.focus();
    await new Promise((resolve) => setTimeout(resolve, 800));
    setOptions([{ value: 'Leaf Garden' }, { value: 'Leaf Studio' }]);
    setState('ready');
  };

  return (
    <Form layout="vertical">
      <FormField label="远程项目">
        <AutoComplete
          ref={input}
          aria-label="远程项目"
          options={options}
          filterOption={false}
          open={open}
          onOpenChange={setOpen}
          loading={state === 'loading'}
          errorContent={
            state === 'error' ? (
              <Flex direction="column" align="start" gap={8}>
                <Text>建议加载失败</Text>
                <Button onClick={retry} size="sm">
                  重试
                </Button>
              </Flex>
            ) : undefined
          }
        />
      </FormField>
      <Text tone="muted" role="status">
        {state === 'loading' ? '正在加载' : state === 'error' ? '加载失败' : '已加载 2 条建议'}
      </Text>
      <Flex>
        <Button
          disabled={state === 'loading'}
          onClick={() => {
            setOptions([]);
            setState('error');
            setOpen(true);
          }}
        >
          模拟失败
        </Button>
      </Flex>
    </Form>
  );
}
```

展开代码

### 禁用与只读

`disabled` 禁用整个控件；`readOnly` 允许聚焦与复制，但不允许编辑、选择或清除。


禁用

只读

states.tsx

复制代码

```tsx lineNumbers file="../../src/examples/auto-complete/states.tsx"
import { AutoComplete, Form, FormField } from '@ifhover/leaf-ui';

const options = [{ value: 'Leaf Garden' }, { value: 'Leaf Studio' }];

export function AutoCompleteStates() {
  return (
    <Form layout="vertical">
      <FormField label="禁用">
        <AutoComplete aria-label="禁用" options={options} defaultValue="Leaf Garden" disabled />
      </FormField>
      <FormField label="只读">
        <AutoComplete aria-label="只读" options={options} defaultValue="Leaf Garden" readOnly />
      </FormField>
    </Form>
  );
}
```

展开代码

支持 `name`、`required`、`form` 等原生输入属性。非受控值随原生表单重置，受控值由应用重置。字段名称和建议内容需要应用自行翻译。


## API

### AutoComplete API

| 属性                  | 类型                                                                                                                    | 默认值            | 说明                                                          |
| ------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------- |
| `options`           | `readonly (`[`AutoCompleteOption`](#autocompleteoption)`\|`[`AutoCompleteOptionGroup`](#autocompleteoptiongroup)`)[]` | 必填             | 该分组内的建议。                                                    |
| `value`             | `string`                                                                                                              | —              | 受控文本；省略时使用内部非受控值。                                           |
| `defaultValue`      | `string`                                                                                                              | `''`           | 非受控模式的初始文本；支持表单重置。                                          |
| `onChange`          | `(value: string) => void`                                                                                             | —              | 输入、清除或选择建议后返回完整文本。                                          |
| `onSelect`          | `(value: string, option: `[`AutoCompleteOption`](#autocompleteoption)`) => void`                                      | —              | 仅选择建议时触发，返回写入的 value 与完整选项。                                 |
| `onSearch`          | `(query: string) => void`                                                                                             | —              | 用户输入时返回查询文字；清除时返回空字符串，选择建议不触发。                              |
| `size`              | `'sm' \| 'md' \| 'lg'`                                                                                                | `'md'`         | 输入框尺寸                                                       |
| `status`            | `'error' \| 'warning'`                                                                                                | —              | 校验状态                                                        |
| `disabled`          | `boolean`                                                                                                             | `false`        | 禁用交互。                                                       |
| `readOnly`          | `boolean`                                                                                                             | `false`        | 锁定业务值，禁止输入、选择、清除和删除。                                        |
| `allowClear`        | `boolean`                                                                                                             | —              | 展示清除操作。                                                     |
| `filterOption`      | `false \| ((query: string, option: `[`AutoCompleteOption`](#autocompleteoption)`) => boolean)`                        | 包含匹配           | `false` 关闭本地过滤；函数可定制过滤                                      |
| `loading`           | `boolean`                                                                                                             | —              | 展示加载状态。                                                     |
| `errorContent`      | `ReactNode`                                                                                                           | —              | 展示加载错误和重试内容。                                                |
| `notFoundContent`   | `ReactNode`                                                                                                           | —              | 没有匹配选项时的内容。                                                 |
| `optionRender`      | `(option: `[`AutoCompleteOption`](#autocompleteoption)`) => ReactNode`                                                | —              | 自定义选项内容。                                                    |
| `open`              | `boolean`                                                                                                             | —              | 受控的展开状态。                                                    |
| `defaultOpen`       | `boolean`                                                                                                             | `false`        | 非受控模式的初始展开状态。                                               |
| `onOpenChange`      | `(open: boolean) => void`                                                                                             | —              | 面板展开或收起时调用。                                                 |
| `virtual`           | `boolean`                                                                                                             | 过滤后超过 100 项时启用 | 仅渲染可见建议；默认在过滤后建议超过 100 项时启用。                                |
| `listHeight`        | `number`                                                                                                              | `248`          | 建议面板的最大可视高度。                                                |
| `optionHeight`      | `number`                                                                                                              | 由主题和密度计算       | 虚拟列表的预估行高；默认由主题和密度计算，实际行会被测量。                               |
| `popupWidth`        | `number \| string`                                                                                                    | `'trigger'`    | 浮层宽度；trigger 与触发控件等宽，auto 按内容定宽（可比控件窄），数字为固定像素值，也支持 CSS 长度。 |
| `popupMaxWidth`     | `number \| string`                                                                                                    | —              | 可选的浮层最大宽度；未设置时不额外限制，仍受可视区域限制。                               |
| `popupPlacement`    | [`PopupOptions`](https://ifhover.github.io/leaf-ui/api/popup-options.md#popupoptions)`['popupPlacement']`             | —              | 浮层相对触发控件的位置。                                                |
| `popupClassName`    | `string`                                                                                                              | —              | 浮层的自定义类名。                                                   |
| `popupStyle`        | [`PopupOptions`](https://ifhover.github.io/leaf-ui/api/popup-options.md#popupoptions)`['popupStyle']`                 | —              | 浮层的自定义样式。                                                   |
| `popupRender`       | [`PopupOptions`](https://ifhover.github.io/leaf-ui/api/popup-options.md#popupoptions)`['popupRender']`                | —              | 包装或补充面板内容，保留传入的内容以维持交互。                                     |
| `getPopupContainer` | [`PopupOptions`](https://ifhover.github.io/leaf-ui/api/popup-options.md#popupoptions)`['getPopupContainer']`          | —              | 返回浮层的挂载容器，也可返回 ShadowRoot。                                  |
| `ref`               | `Ref<HTMLInputElement>`                                                                                               | —              | 输入框引用                                                       |

`placeholder`、`name`、`required`、`form`、`maxLength`、`aria-*` 等属性传递给输入框；`className` 和 `style` 作用于外层容器。

#### AutoCompleteOption

| 属性            | 类型          | 默认值     | 说明                                 |
| ------------- | ----------- | ------- | ---------------------------------- |
| `value`       | `string`    | 必填      | 唯一建议值；选择后写入输入框。                    |
| `label`       | `ReactNode` | —       | 建议的显示文字；默认也用于本地过滤。                 |
| `searchLabel` | `string`    | —       | 搜索纯文本；省略时使用字符串 label，其他内容使用 value。 |
| `disabled`    | `boolean`   | `false` | 禁用该建议。                             |

#### AutoCompleteOptionGroup

| 属性        | 类型                                                         | 默认值 | 说明       |
| --------- | ---------------------------------------------------------- | --- | -------- |
| `label`   | `ReactNode`                                                | 必填  | 建议分组的标题。 |
| `options` | `readonly `[`AutoCompleteOption`](#autocompleteoption)`[]` | 必填  | 该分组内的建议。 |
