# 搜索框 SearchBar

- 页面: https://jiguang132.com/zh/resources/ant-design-mobile/docs/search-bar
- 资源: Ant Design Mobile (https://jiguang132.com/zh/resources/ant-design-mobile.md)
- 全部指南: https://jiguang132.com/zh/resources/ant-design-mobile/docs.md

搜索场景的输入框组件。

## 安装

```bash
npm install antd-mobile@5.43.0
```

antd-mobile 是移动网页组件库，不是 React Native 或小程序组件。React 19 项目需在入口用 `unstableSetRender` 注册 `createRoot`，否则 Toast、Dialog 等命令式 API 无法渲染；深色模式通过 `<html data-prefers-color-scheme="dark">` 切换。

示例来自 Ant Design Mobile 官方仓库（MIT），固定在 npm 5.43.0 对应的提交；示例中的 `DemoBlock` 等展示辅助组件由 JGuang 重写，不属于 antd-mobile 的 API。

搜索场景的输入框组件。

## 何时使用

在信息池中缩小范围，快速而轻松地获取目标信息。

## 示例

## SearchBar

### 属性

| 属性 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| cancelText | 取消按钮的文案 | `string` | `'取消'` |
| clearOnCancel | 点击取消按钮后是否清空输入框 | `boolean` | `true` |
| clearable | 是否启用清除图标，点击清除图标后会清空输入框 | `boolean` | `true` |
| searchIcon | 自定义搜索图标 | `ReactNode` | `<SearchOutline />` |
| maxLength | 输入的最大字符数 | `number` | - |
| onBlur | 输入框失去焦点时触发 | `(e: React.FocusEvent<HTMLInputElement>) => void` | - |
| onCancel | 点击取消按钮时触发 | `() => void` | - |
| onChange | 输入框内容变化时触发 | `(value: string) => void` | - |
| onClear | 点击清除按钮后触发 | `() => void` | - |
| onFocus | 输入框获得焦点时触发 | `(e: React.FocusEvent<HTMLInputElement>) => void` | - |
| onSearch | 输入框回车时触发 | `(value: string) => void` | - |
| onlyShowClearWhenFocus | 如果 `true`，那么只有输入框聚焦时才会显示清除按钮；如果为 `false`，那么输入框失去焦点后依旧会显示清除按钮 | `boolean` | `false` |
| placeholder | 提示文本 | `string` | - |
| showCancelButton | 是否在搜索框右侧显示取消按钮 | `boolean \| ((focus: boolean, value: string) => boolean)` | `false` |
| value | 输入值 | `string` | - |

此外还支持以下原生属性：`onCompositionStart` `onCompositionEnd` `autoFocus`

### CSS 变量

| 属性                | 说明                   | 默认值                  |
| ------------------- | ---------------------- | ----------------------- |
| --background        | 背景色                 | `#f5f5f5`               |
| --border-radius     | 圆角                   | `6px`                   |
| --height            | 高度                   | `32px`                  |
| --padding-left      | 搜索框的左侧 padding   | `8px`                   |
| --placeholder-color | `placeholder` 文字颜色 | `var(--adm-color-weak)` |

## Ref

同 [Input](/zh/components/input)

## FAQ

### 键盘按钮没有显示"搜索"，而是"返回"

属性 `enterkeyhinit` 只能在 `Android` 版本 4.4.5 及以上或者 `IOS` 版本 13.4 及以上使用，更多细节见此 [issue](https://github.com/ant-design/ant-design-mobile/issues/5545)

---

JGuang 全部资源索引: https://jiguang132.com/llms.txt
