> 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/reactjs-javascript.md).

# 在 React JavaScript 应用中嵌入体验

在用 JavaScript 编写的 React 应用中安装 Pixel Streaming Embed 包，渲染已发布的体验，并通过你自己的按钮启动它。

在用 JavaScript 编写的 React 应用中渲染已发布的 Convai Pixel Streaming 体验。该组件及其选项与 TypeScript 中相同，只是不包含类型注解。最后，用户启动体验后，它会在你的页面中播放。

### 前提条件

* 一个使用 Vite 之类打包器的 React 18 应用。
* 已发布体验的体验 ID，以及一种授权方式：返回 Convai 身份验证令牌的服务器路由，或已被 Convai 列入允许列表的域名。参见 [发布并授权体验](/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 %}

### 渲染体验

此示例从你服务器上的路由获取身份验证令牌， `/api/convai-token`，然后通过其自己的开始按钮渲染体验。 `PixelStreamComponent` 会填充其父元素，因此请给父元素设置尺寸：

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

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

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

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

  如果没有 token，则返回 <p>加载中…</p>;

  return (
    <div style={{ width: '100%', height: '100vh' }}>
      <PixelStreamComponent
        ref={streamRef}
        expId="YOUR_EXPERIENCE_ID"
        authToken={token}
        InitialScreen={
          <button onClick={() => streamRef.current?.initializeExperience()}>
            开始体验
          </button>
        }
        onIframeLoaded={() => console.log('Experience loaded')}
      />
    </div>
  );
}
```

{% endcode %}

如果 Convai 已将你的域名列入允许列表，则省略 `authToken` 并直接渲染该组件。没有 `InitialScreen`，该组件会显示一个 **点击以开始你的体验** 点击即可启动体验的屏幕。

### 控制体验

一旦 `onIframeLoaded` 触发后，即可调用 ref 上的方法，例如 `streamRef.current?.enableCamera()` 或 `streamRef.current?.sendMessageToCharacter('Hello')`。该 [Pixel Streaming Embed API 参考](/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/api-reference.md) 列出了所有方法和回调。

### 验证嵌入

加载页面并选择 **开始体验**.

{% hint style="success" %}
该体验会替换按钮，浏览器控制台会输出 `体验已加载`.
{% endhint %}

如果嵌入显示的是错误消息，请参阅 [故障排查](/api-docs/zh/cha-jian-yu-ji-cheng/convai-pixel-streaming-embed/react-typescript.md#troubleshooting) TypeScript 页面上的内容；原因相同。

### 后续步骤

{% content-ref url="/pages/87b57936662c69d8802f20f500191b181163cf02" %}
[Pixel Streaming Embed API 参考](/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/reactjs-javascript.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.
