> For the complete documentation index, see [llms.txt](https://gitbook.com/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.com/docs/documentation/zh/publish/embedding/implementation/react.md).

# React

使用预构建的 React 组件将 Docs Embed 添加到你的 React 应用中

对于 React 项目，GitBook 提供了预构建组件，让嵌入文档变得简单且符合惯用方式。这些组件会自动处理状态管理、上下文和生命周期。

## 步骤

{% stepper %}
{% step %}
**安装软件包**

将 `@gitbook/embed` 添加到你的 React 项目中：

```bash
npm install @gitbook/embed
```

完整的 API 参考和源代码，请参阅 GitHub 上的 [`@gitbook/embed` 软件包](https://github.com/GitbookIO/gitbook/tree/main/packages/embed).
{% endstep %}

{% step %}
**导入 React 组件**

导入 `GitBookProvider` 和 `GitBookFrame` 组件：

```jsx
import {
  GitBookProvider,
  GitBookFrame,
} from "@gitbook/embed/react";
```

{% endstep %}

{% step %}
**使用 GitBookProvider 包裹应用**

在组件树的根节点或需要嵌入内容的位置添加 Provider：

```jsx
function App() {
  return (
    <GitBookProvider siteURL="https://docs.company.com">
      <YourAppContent />
    </GitBookProvider>
  );
}
```

{% endstep %}

{% step %}
**添加 GitBookFrame 组件**

将 Frame 组件放在你想显示嵌入内容的位置：

```jsx
function App() {
  return (
    <GitBookProvider siteURL="https://docs.company.com">
      <div className="app">
        <YourAppContent />
        <GitBookFrame
          visitor={{
            token: 'your-jwt-token', // 可选：用于自适应内容或经过身份验证的访问
            unsignedClaims: { userId: '123' } // 可选：用于动态表达式的自定义声明
          }}
        />
      </div>
    </GitBookProvider>
  );
}
```

{% hint style="info" %}
如果使用 Assistant 选项卡，请在呈现嵌入内容的 iframe 上设置 `allow="clipboard-write"` 。React 集成由你的应用负责设置 iframe。独立的 [Script 标签](https://gitbook.com/docs/documentation/zh/publish/embedding/implementation/script.md) 实现会自动添加此设置。
{% endhint %}
{% endstep %}

{% step %}
**自定义嵌入内容**

向 Frame 组件传递配置属性：

```jsx
<GitBookProvider siteURL="https://docs.company.com">
  <GitBookFrame
    trademark={false}
    tabs={['assistant', 'search', 'docs']}
    colorScheme="dark"
    greeting={{ title: 'Welcome!', subtitle: 'How can I help?' }}
    assistantName="Support Copilot"
    closeButton={true}
    suggestions={['What is GitBook?', 'How do I get started?']}
    actions={[
      {
        icon: 'circle-question',
        label: '联系支持团队',
        onClick: () => window.open('https://support.example.com', '_blank')
      }
    ]}
    tools={[/* ... */]}
    visitor={{
      token: 'your-jwt-token',
      unsignedClaims: { userId: '123' }
    }}
  />
</GitBookProvider>
```

如果省略 `colorScheme`，嵌入内容会遵循 iframe 的 CSS `color-scheme`。这样它就能自动匹配应用主题。
{% endstep %}

{% step %}
**使用 useGitBook hook 控制嵌入内容**

使用 `useGitBook` 钩子以编程方式与嵌入内容交互：

```jsx
import { useGitBook } from "@gitbook/embed/react";

function HelpButton() {
  const gitbook = useGitBook();
  const frameURL = gitbook.getFrameURL({ visitor: { token: '...' } });
  
  const handleNavigate = () => {
    const iframe = document.createElement('iframe');
    iframe.src = frameURL;
    iframe.allow = 'clipboard-write';
    const frame = gitbook.createFrame(iframe);
    frame.navigateToPage('/getting-started');
    frame.navigateToAssistant();
    frame.postUserMessage('How do I get started?');
  };

  return <button onClick={handleNavigate}>获取帮助</button>;
}
```

{% endstep %}

{% step %}
**有条件地渲染嵌入内容**

仅在需要时显示嵌入内容：

```jsx
function App() {
  const [showEmbed, setShowEmbed] = useState(false);

  return (
    <GitBookProvider siteURL="https://docs.company.com">
      <button onClick={() => setShowEmbed(true)}>获取帮助</button>
      {showEmbed && <GitBookFrame />}
    </GitBookProvider>
  );
}
```

{% endstep %}

{% step %}
**与 Next.js 或服务器端渲染搭配使用**

动态导入组件以避免 SSR 问题：

```jsx
import dynamic from "next/dynamic";

const GitBookProvider = dynamic(
  () => import("@gitbook/embed/react").then((mod) => mod.GitBookProvider),
  { ssr: false }
);

const GitBookFrame = dynamic(
  () => import("@gitbook/embed/react").then((mod) => mod.GitBookFrame),
  { ssr: false }
);
```

{% endstep %}
{% endstepper %}

## 属性与配置

**GitBookProvider 属性：**

| 属性         | 类型          | 必填 | 默认  | 说明                                               |
| ---------- | ----------- | -- | --- | ------------------------------------------------ |
| `siteURL`  | `string`    | 是  | 不适用 | GitBook 文档站点的网址（例如， `https://docs.company.com`). |
| `children` | `ReactNode` | 是  | 不适用 | 要在 Provider 中渲染的子组件。                             |

**GitBookFrame 属性：**

所有配置选项都可以作为属性传递给 `<GitBookFrame>`。可用选项请参阅下方的“配置”部分。

| 属性              | 类型                  | 必填 | 默认                     | 说明               |
| --------------- | ------------------- | -- | ---------------------- | ---------------- |
| `className`     | `string`            | 否  | `null`                 | 应用于框架容器的 CSS 类名。 |
| `style`         | `object`            | 否  | `{}`                   | 应用于框架容器的内联样式。    |
| `colorScheme`   | `'light' \| 'dark'` | 否  | 继承自 CSS `color-scheme` | 覆盖嵌入内容的配色方案。     |
| `assistantName` | `string`            | 否  | `null`                 | 覆盖 UI 中显示的助手名称。  |
| `closeButton`   | `boolean`           | 否  | `null`                 | 在助手中显示关闭按钮。      |
| `visitor`       | `object`            | 否  | `{}`                   | 身份验证访问选项（见下文）。   |

**useGitBook Hook：**

返回一个 `GitBookClient` 实例，包含以下方法：

* `getFrameURL(options?: { visitor?: {...}, colorScheme?: 'light' | 'dark' })` → `string` - 获取 iframe URL
* `createFrame(iframe: HTMLIFrameElement)` → `GitBookFrameClient` - 创建 frame 客户端

frame 客户端提供：

* `navigateToPage(path: string)` → `void`
* `navigateToAssistant()` → `void`
* `postUserMessage(message: string)` → `void`
* `clearChat()` → `void`
* `configure(settings: {...})` → `void`
* `on(event: string, listener: Function)` → `() => void`

## 配置选项

配置选项可作为 props 传递给 `<GitBookFrame>`:

### `tabs`

覆盖显示哪些选项卡。

搜索默认处于启用状态。如果设置了 `tabs`，嵌入内容将只显示你列出的标签页。

* **类型**: `('assistant' | 'search' | 'docs')[]`

### `colorScheme`

覆盖嵌入内容的配色方案。

如果省略，嵌入内容会遵循 iframe 的 CSS `color-scheme`，从而继承父页面或浏览器的偏好设置。

* **类型**: `'light' | 'dark'`

### `actions`

在侧边栏中与选项卡一同呈现的自定义操作按钮。点击每个操作按钮时都会触发回调。

**注意**：此选项之前名为 `buttons`。请改用 `actions` 。

* **类型**: `Array<{ icon: string, label: string, onClick: () => void }>`

### `greeting`

显示在助手选项卡中的欢迎消息。

* **类型**: `{ title: string, subtitle: string }`

### `assistantName`

覆盖 UI 中显示的助手名称。

* **类型**: `string`
* **最大长度**: `32` 个字符

### `closeButton`

在助手中显示关闭按钮。

* **类型**: `boolean`

### `suggestions`

显示在助手欢迎界面中的建议问题。

* **类型**: `string[]`

### `trademark`

显示或隐藏嵌入式 UI 中的 GitBook 商标，包括 Docs Embed 页脚和助手品牌标识。

* **类型**: `boolean`
* **默认值**: `true`

### `tools`

用于扩展 Assistant 的自定义 AI 工具。详情请参阅 [创建自定义工具](https://gitbook.com/docs/documentation/zh/publish/embedding/configuration/creating-custom-tools.md) 。

* **类型**: `Array<{ name: string, description: string, inputSchema: object, execute: Function, confirmation?: {...} }>`

### `visitor` （经过身份验证的访问）

用于 [自适应内容](https://gitbook.com/docs/documentation/zh/publish/adaptive-content.md) 和 [身份验证访问](https://gitbook.com/docs/documentation/zh/publish/site-audience/authenticated-access.md).

* **类型**: `{ token?: string, unsignedClaims?: Record<string, unknown> }`

## 常见问题

* **未使用 GitBookProvider 包裹** – `GitBookFrame` 需要父级 `GitBookProvider` 才能正常运行。
* **在 SSR 中使用时未进行动态导入** – 该组件使用浏览器 API，在 Next.js 或其他 SSR 框架中必须通过动态导入加载。
* **siteURL 与已发布文档不匹配** – 确保 `siteURL` 属性与线上文档站点的 URL 完全一致。
* **在 provider 外调用 useGitBook** – `useGitBook` 钩子必须在作为 `GitBookProvider`.
* **子级的组件中使用** – 避免嵌套多个 `GitBookProvider` 实例，以免造成上下文冲突。
* **使用旧组件名称** – 该组件现在名为 `GitBookFrame`，而不是 `GitBookAssistantFrame`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://gitbook.com/docs/documentation/zh/publish/embedding/implementation/react.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
