> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/react-typescript.md).

# 在 React TypeScript 应用中嵌入体验

在 React TypeScript 应用中安装 Pixel Streaming Embed 包，渲染已发布的体验，并通过你自己的界面进行控制。

在使用 TypeScript 编写的 React 应用中渲染已发布的 Convai Pixel Streaming 体验，并通过自己的代码控制摄像头、音频、麦克风和聊天。完成后，用户点击启动，体验便会在页面内播放。

### 前提条件

* 使用 TypeScript 编写的 React 18 应用，并配备 Vite 等打包工具。
* 已发布体验的 ID，以及一种授权方式：用于返回 Convai 身份验证令牌的服务器路由，或已添加到 Convai 允许列表中的域名。请参阅 [发布并授权体验](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/whitelisting-and-publishing-an-experience.md).

### 安装软件包

当前版本为 <code class="expression">space.vars.experience\_embed\_version</code>.

{% tabs %}
{% tab title="npm" %}

```bash
npm install @convai/experience-embed
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @convai/experience-embed
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @convai/experience-embed
```

{% endtab %}
{% endtabs %}

### 渲染体验

`PixelStreamComponent` 会为体验请求会话，并在 iframe 中渲染体验。它会填满其父元素，因此请为父元素设置尺寸。本示例会先从服务器上的路由获取身份验证令牌， `/api/convai-token`，然后再渲染组件：

{% code title="src/App.tsx" %}

```tsx
import { useEffect, useRef, useState } from 'react';
import {
  PixelStreamComponent,
  type PixelStreamComponentHandles,
} from '@convai/experience-embed';

export default function App() {
  const streamRef = useRef<PixelStreamComponentHandles>(null);
  const [token, setToken] = useState<string>();

  useEffect(() => {
    fetch('/api/convai-token')
      .then((response) => response.json())
      .then((body: { token: string }) => setToken(body.token));
  }, []);

  if (!token) return <p>Loading…</p>;

  return (
    <div style={{ width: '100%', height: '100vh' }}>
      <PixelStreamComponent
        ref={streamRef}
        expId="YOUR_EXPERIENCE_ID"
        authToken={token}
        onIframeLoaded={() => console.log('Experience loaded')}
      />
    </div>
  );
}
```

{% endcode %}

如果 Convai 已将你的域名添加到允许列表中，则省略 `authToken` 并直接渲染组件即可。

{% hint style="warning" %}
在渲染组件之前获取令牌，并在整个会话期间保留该令牌。新的 `authToken`, `expId`或 `endUserId` 值会请求一个新会话，并重新加载体验。
{% endhint %}

### 启动体验

组件首先会显示一个 **点击以启动体验** 画面；用户点击后，体验便会启动。若要显示自定义画面，请将其作为 `InitialScreen`。自定义屏幕不会自行启动体验，因此请调用 `initializeExperience()` ：

```tsx
<PixelStreamComponent
  ref={streamRef}
  expId="YOUR_EXPERIENCE_ID"
  authToken={token}
  InitialScreen={
    <button onClick={() => streamRef.current?.initializeExperience()}>
      开始导览
    </button>
  }
  LoadingScreenComponent={<p>正在准备体验…</p>}
/>
```

`LoadingScreenComponent` 会覆盖 iframe，直到流页面报告已完成加载。

### 控制体验

在 `onIframeLoaded` 触发后再调用 ref 上的方法。在此之前调用方法不会发送任何内容：

```tsx
await streamRef.current?.enableCamera();
streamRef.current?.disableCharacterAudio();
streamRef.current?.sendMessageToCharacter('Where is the fire exit?');
streamRef.current?.muteMicrophone();
streamRef.current?.setChatStyle({ backgroundOpacity: 0.3 });
```

若要跟踪体验中的动态，请将 `onCharacterMessage` 和 `onMicStatus` 等回调作为 props 传入。 [Pixel Streaming Embed API 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/api-reference.md) 列出了所有方法、回调和载荷。

### 验证嵌入

加载页面并点击启动屏幕。

{% hint style="success" %}
体验将替换启动屏幕，并且浏览器控制台会记录 `Experience loaded`.
{% endhint %}

### 故障排查

#### 嵌入内容提示你联系 Convai

**症状：** 嵌入内容显示 `Please contact convai to get <origin> whitelisted!` ，而不是启动屏幕。

**原因：** 嵌入内容没有 `authToken`，且页面域名未列入你账户的允许列表，或者体验 ID 有误。

**解决方法：** 传入身份验证令牌，或请 Convai 将该域名加入允许列表。检查体验 ID。

**验证：** 重新加载页面。启动屏幕应会出现。

#### 嵌入内容报告身份验证令牌无效

**症状：** 嵌入内容显示 `This experience couldn't start: the Convai auth token is invalid or has expired.`

**原因：** Convai 拒绝了作为 `authToken`.

**修复方法：** 在服务器上生成一个新令牌，然后使用该令牌重新渲染组件。

**验证：** 重新加载页面。启动屏幕应会出现。

#### 点击自定义起始屏幕后没有任何反应

**症状：** 页面会显示你的 `InitialScreen`，点击它却无法启动体验。

**原因：** 自定义 `InitialScreen` 会替换默认屏幕及其点击处理程序。

**修复方法：** 从屏幕的 ref 调用 `initializeExperience()` 。

**验证：** 点击屏幕后，体验会显示出来。

### 后续步骤

{% content-ref url="/pages/87b57936662c69d8802f20f500191b181163cf02" %}
[Pixel Streaming Embed API 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/api-reference.md)
{% endcontent-ref %}


---

# 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://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/react-typescript.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.
