Files
simple-react-app-kit/packages/search/docs/zh-Hans/examples/global-search.mdx
T

59 lines
1.4 KiB
Plaintext

---
title: 全局搜索示例
description: 组合触发器、对话框、历史记录和结果导航。
order: 30
toc:
- id: define-results
title: 定义结果
- id: handle-selection
title: 处理选择
- id: control-history
title: 控制历史记录
---
## 定义结果 {#define-results}
```ts
const searchAdapter: SearchAdapter = {
async search({ query }) {
return {
groups: [
{
id: "docs",
label: "文档",
items: documents
.filter((document) => document.title.includes(query))
.map((document) => ({
id: document.slug,
title: document.title,
description: document.description,
payload: { href: `/docs/${document.slug}` },
})),
},
],
}
},
}
```
## 处理选择 {#handle-selection}
```tsx
<SearchProvider
adapter={searchAdapter}
onSelect={({ item }) => {
const payload = item.payload as { href: string }
router.navigate({ to: payload.href })
}}
>
<HeaderSearchButton />
<SearchDialog />
</SearchProvider>
```
不方便渲染 `SearchTrigger` 的位置可以调用 `searchDialogHandle.open(null)`。
## 控制历史记录 {#control-history}
历史记录默认保存在 `workspace-search-history`。为不同产品传入独立的 `historyStorageKey`,或者设置为 `false`,让历史只存在于当前内存会话中。