> 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/fa-bu/embedding/implementation/react.md).

# 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` components:

```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"` 用于渲染嵌入内容的 iframe。React 集成会将 iframe 的设置留给你的应用。独立 [Script 标签](/docs/documentation/zh/fa-bu/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: '欢迎！', subtitle: '我能帮你什么？' }}
    assistantName="支持副驾"
    closeButton={true}
    suggestions={['什么是 GitBook？', '我该如何开始？']}
    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` hook 可用于以编程方式与嵌入内容交互：

```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('我该如何开始？');
  };

  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 文档站点 URL（例如， `https://docs.company.com`). |
| `children` | `ReactNode` | 是  | 不适用 | 要在 provider 中渲染的子组件。                                 |

**GitBookFrame 属性：**

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

| 属性              | 类型                  | 必需 | 默认                      | 说明                       |
| --------------- | ------------------- | -- | ----------------------- | ------------------------ |
| `className`     | `string`            | 否  | `null`                  | 要应用到 frame 容器的 CSS 类名。   |
| `style`         | `object`            | 否  | `{}`                    | 要应用到 frame 容器的内联样式。      |
| `colorScheme`   | `'light' \| 'dark'` | 否  | 从 CSS 继承 `color-scheme` | 覆盖嵌入的配色方案。               |
| `assistantName` | `string`            | 否  | `null`                  | 覆盖 UI 中显示的 assistant 名称。 |
| `closeButton`   | `boolean`           | 否  | `null`                  | 在 Assistant 内部显示一个关闭按钮。  |
| `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`

## 配置选项

配置选项可作为 `<GitBookFrame>`:

### `tabs`

覆盖显示的选项卡。

搜索默认启用。如果你设置 `tabs`，嵌入内容将仅显示你列出的选项卡。

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

### `colorScheme`

覆盖嵌入的配色方案。

如果省略，嵌入将遵循 iframe 的 CSS `color-scheme`，这使其可以继承父页面或浏览器的偏好设置。

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

### `actions`

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

**注意**：这之前被称为 `buttons`。请改用 `actions` 。

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

### `greeting`

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

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

### `assistantName`

覆盖 UI 中显示的 assistant 名称。

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

### `closeButton`

在 Assistant 内部显示一个关闭按钮。

* **类型**: `boolean`

### `suggestions`

显示在 Assistant 欢迎屏幕中的建议问题。

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

### `trademark`

在嵌入 UI 中显示或隐藏 GitBook 商标——包括 Docs Embed 页脚和 Assistant 品牌标识。

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

### `tools`

用于扩展 Assistant 的自定义 AI 工具。详情请参见 [创建自定义工具](/docs/documentation/zh/fa-bu/embedding/configuration/creating-custom-tools.md) 。

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

### `visitor` （已认证访问）

用于 [自适应内容](/docs/documentation/zh/fa-bu/adaptive-content.md) 并 [经过身份验证的访问](/docs/documentation/zh/fa-bu/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` hook 必须在作为 `GitBookProvider`.
* **树中存在多个 provider** – 避免嵌套多个 `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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://gitbook.com/docs/documentation/zh/fa-bu/embedding/implementation/react.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
