# @a2ui-sdk/react 中文文档

规范地址：https://npmcn.com/package/%40a2ui-sdk/react/

版本：0\.4\.0
npm 元数据更新时间：2026-02-02T07:39:41.066Z
中文译文更新时间：2026-11-05T23:13:40.034Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40a2ui-sdk/react
原文对照：https://npmcn.com/package/%40a2ui-sdk/react/?lang=original
项目主页：https://a2ui-sdk.js.org/
源码仓库：https://github.com/easyops-cn/a2ui-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：178 kB，174 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：14 个
- peer 依赖：react ^19\.0\.0，react-dom ^19\.0\.0
- 首次发布：2026-01-13T07:35:06.506Z
- 最新版本发布：2026-02-02T07:39:40.900Z
- 近 30 天下载量：9799（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：11（近 12 个月 11 个）

## 中文简介

A2UI SDK 反应

## 安装

```sh
npm install @a2ui-sdk/react
```

也可以使用：`pnpm add @a2ui-sdk/react`、`yarn add @a2ui-sdk/react`、`bun add @a2ui-sdk/react`

## README

# @ a2ui- sdk/ 反应

渲染 A2UI 协议的反应执行 。 此软件包提供 React 组件和钩子,用于将 A2UI 渲染器集成到您的应用程序中.

## 安装

```bash
npm install @a2ui-sdk/react
```

### 同伴依赖关系

-   `react` ^19.0
-   `react-dom` ^19.0

## 使用量

### v. 0.8 (中文(简体) )

#### 基本用途

```tsx
import {
  A2UIProvider,
  A2UIRenderer,
  type A2UIMessage,
  type A2UIAction,
} from '@a2ui-sdk/react/0.8'

function App() {
  const messages: A2UIMessage[] = [
    // A2UI messages from your backend
  ]

  const handleAction = (action: A2UIAction) => {
    console.log('Action received:', action)
  }

  return (
    <A2UIProvider messages={messages}>
      <A2UIRenderer onAction={handleAction} />
    </A2UIProvider>
  )
}
```

#### 自定义组件

您可以通过 `catalog` 打开道具 `A2UIProvider`启用 `standardCatalog` 作为基础,并用您的自定义组件扩展它.

```tsx
import {
  A2UIProvider,
  A2UIRenderer,
  standardCatalog,
  type A2UIMessage,
  type A2UIAction,
} from '@a2ui-sdk/react/0.8'

// Extend standard catalog with custom components
const customCatalog = {
  ...standardCatalog,
  components: {
    ...standardCatalog.components,
    // Override default Button component with a custom one
    Button: CustomButtonComponent,
    // Add a new custom Switch component
    Switch: CustomSwitchComponent,
  },
}

function App() {
  return (
    <A2UIProvider catalog={customCatalog} messages={messages}>
      <A2UIRenderer onAction={handleAction} />
    </A2UIProvider>
  )
}
```

执行带有动作调度的自定义按钮组件 :

```tsx
import {
  useDispatchAction,
  ComponentRenderer,
  type ButtonComponentProps,
} from '@a2ui-sdk/react/0.8'

export function CustomButtonComponent({
  surfaceId,
  componentId,
  child,
  action,
}: ButtonComponentProps) {
  const dispatchAction = useDispatchAction()

  const handleClick = () => {
    if (action) {
      dispatchAction(surfaceId, componentId, action)
    }
  }

  return (
    <button onClick={handleClick}>
      <ComponentRenderer surfaceId={surfaceId} componentId={child} />
    </button>
  )
}
```

执行带有数据约束的自定义开关组件:

```tsx
import { useDataBinding, useFormBinding } from '@a2ui-sdk/react/0.8'

export function CustomSwitchComponent({
  surfaceId,
  componentId,
  label,
  value,
}: SwitchComponentProps) {
  const labelText = useDataBinding<string>(surfaceId, label, '')
  const [checked, setChecked] = useFormBinding<boolean>(surfaceId, value, false)

  const handleChange = (newChecked: boolean) => {
    setChecked(newChecked)
  }

  return (
    <Switch checked={checked} onChange={handleChange}>
      {labelText}
    </Switch>
  )
}
```

### 页:1

#### 基本用途

```tsx
import {
  A2UIProvider,
  A2UIRenderer,
  type A2UIMessage,
  type A2UIAction,
} from '@a2ui-sdk/react/0.9'

function App() {
  const messages: A2UIMessage[] = [
    // A2UI messages from your backend
  ]

  const handleAction = (action: A2UIAction) => {
    console.log('Action:', action.name, action.context)
  }

  return (
    <A2UIProvider messages={messages}>
      <A2UIRenderer onAction={handleAction} />
    </A2UIProvider>
  )
}
```

#### 自定义组件

覆盖或扩展标准目录的方式与v0.8相同:

```tsx
import {
  A2UIProvider,
  A2UIRenderer,
  standardCatalog,
  type A2UIMessage,
  type A2UIAction,
} from '@a2ui-sdk/react/0.9'

// Extend standard catalog with custom components
const customCatalog = {
  ...standardCatalog,
  components: {
    ...standardCatalog.components,
    // Override default components or add new ones
    Button: CustomButtonComponent,
  },
}

function App() {
  return (
    <A2UIProvider catalog={customCatalog} messages={messages}>
      <A2UIRenderer onAction={handleAction} />
    </A2UIProvider>
  )
}
```

## 出口

### v0.9 (最晚) (中文(简体) )

```tsx
import {
  // Components
  A2UIProvider,
  A2UIRenderer,
  ComponentRenderer,

  // Catalog
  standardCatalog,

  // Hooks
  useDispatchAction,
  useDataBinding,
  useFormBinding,
  useStringBinding,
  useDataModel,
  useValidation,
  useSurfaceContext,
  useScope,
  useScopeBasePath,
  useA2UIMessageHandler,

  // Context Providers & Hooks
  ActionProvider,
  useActionContext,

  // Types
  type A2UIMessage,
  type A2UIAction,
  type A2UIProviderProps,
  type A2UIRendererProps,
  type ComponentsMap,
  type Component,
  type Action,
  type DynamicValue,
  type DynamicString,
  type DynamicNumber,
  type DynamicBoolean,
  type DynamicStringList,
  type ChildList,
  type TemplateBinding,
  type CheckRule,
  type Checkable,
  type ValidationResult,
  type ScopeValue,
  type DataModel,
  type A2UIMessageHandler,
} from '@a2ui-sdk/react/0.9'
```

### v. 0.8 (中文(简体) )

```tsx
import {
  // Components
  A2UIProvider,
  A2UIRenderer,
  ComponentRenderer,

  // Catalog
  standardCatalog,

  // Hooks
  useDispatchAction,
  useDataBinding,
  useFormBinding,
  useSurfaceContext,
  useDataModelContext,
  useScope,
  useScopeBasePath,
  useA2UIMessageHandler,

  // Context Providers & Hooks
  ActionProvider,
  useActionContext,

  // Types
  type A2UIMessage,
  type A2UIAction,
  type A2UIProviderProps,
  type A2UIRendererProps,
  type ComponentsMap,
  type Action,
  type ValueSource,
  type ScopeValue,
  type A2UIMessageHandler,
} from '@a2ui-sdk/react/0.8'
```

### 命名空间导入

```tsx
import { v0_8, v0_9 } from '@a2ui-sdk/react'

// Use v0.9 API
const { A2UIProvider, A2UIRenderer } = v0_9
```

## 递增信件处理

**V0.8 & v0.9 中新建** : 对于递增接收信件的应用程序(例如通过WebSocket或SSE),您可以使用 `useA2UIMessageHandler` 钩键以驱动新消息而不清除状态 。 这保存了用户编辑功能.

### 问题

使用时 `messages` 打开道具 `A2UIProvider`,更改消息阵列会让提供者从头清除所有状态并重新处理. 这将失去用户编辑 :

```tsx
// ❌ This loses user edits when new messages arrive
function App() {
  const [messages, setMessages] = useState<A2UIMessage[]>([])

  useEffect(() => {
    const ws = new WebSocket('ws://example.com')
    ws.onmessage = (event) => {
      const newMessage = JSON.parse(event.data)
      setMessages((prev) => [...prev, newMessage]) // Triggers full clear & reprocess!
    }
  }, [])

  return (
    <A2UIProvider messages={messages}>
      <A2UIRenderer onAction={handleAction} />
    </A2UIProvider>
  )
}
```

### 解决方案

使用 `useA2UIMessageHandler` 连接到递增处理信件 :

```tsx
import {
  A2UIProvider,
  A2UIRenderer,
  useA2UIMessageHandler,
  type A2UIMessage,
  type A2UIAction,
} from '@a2ui-sdk/react/0.8' // or '@a2ui-sdk/react/0.9'

function App() {
  const handleAction = (action: A2UIAction) => {
    console.log('Action:', action)
  }

  return (
    <A2UIProvider>
      <MessageHandler>
        <A2UIRenderer onAction={handleAction} />
      </MessageHandler>
    </A2UIProvider>
  )
}

function MessageHandler({ children }: { children: React.ReactNode }) {
  const { processMessage } = useA2UIMessageHandler()

  useEffect(() => {
    // Listen for incremental updates
    const ws = new WebSocket('ws://example.com')
    ws.onmessage = (event) => {
      const newMessage = JSON.parse(event.data)
      processMessage(newMessage) // Incremental - preserves user edits!
    }

    return () => ws.close()
  }, [processMessage])

  return <>{children}</>
}
```

这个 `useA2UIMessageHandler` 钩子返回 :

-   **`processMessage(message: A2UIMessage)`**: 递增处理单个消息
-   **`processMessages(messages: A2UIMessage[])`**: 按顺序处理多条消息
-   **`clear()`**: 清除所有表面和状态( 不需要)

## 钩子

### 使用 A2UIMessage 汉德勒

见 [递增信件处理](https://npmcn.com/package/%40a2ui-sdk/react/#readme-incremental-message-handling) 详情见上文.

### 使用数据框

确定数据模型的动态值:

```tsx
const value = useDataBinding({ path: '/user/name' })
// Returns the value at /user/name in the data model
```

### 使用FormBinding

形式组件双向绑定:

```tsx
const [value, setValue] = useFormBinding({ path: '/form/email' })
// value: current value
// setValue: update the data model
```

### 使用发送动作

从自定义组件发送动作 :

```tsx
const dispatch = useDispatchAction()

const handleClick = () => {
  dispatch({
    name: 'submit',
    context: { formId: 'contact' },
  })
}
```

### 参数

对照检查规则验证窗体输入 :

```tsx
const { valid, errors } = useValidation(checks)
// valid: boolean
// errors: string[] - list of failed validation messages
```

### 动作 提供和使用动作关联

对于高级使用大小写,您可以通过使用 `ActionProvider` 财务报告和审定财务报表 `useActionContext` 直接说 当您需要截取、转换或增强动作时.

```tsx
import {
  A2UIProvider,
  A2UIRenderer,
  ActionProvider,
  useActionContext,
} from '@a2ui-sdk/react/0.9'

function ActionLogger({ children }: { children: React.ReactNode }) {
  const { onAction } = useActionContext()

  // You can access the action handler here
  // and potentially wrap it with logging or other middleware logic

  return <>{children}</>
}

function App() {
  const handleAction = (action: A2UIAction) => {
    console.log('Action:', action)
  }

  return (
    <A2UIProvider messages={messages}>
      <ActionProvider onAction={handleAction}>
        <ActionLogger>
          <A2UIRenderer />
        </ActionLogger>
      </ActionProvider>
    </A2UIProvider>
  )
}
```

**说明:** 在大多数情况下,你不需要使用 `ActionProvider` 直接为 `A2UIProvider` 已经包括了 仅用于高级定制方案 .

## 许可证

阿帕奇 - 2.0

## 常见问题

### @a2ui-sdk/react 是什么？

A2UI SDK 反应

### 如何安装 @a2ui-sdk/react？

在项目目录运行 npm install @a2ui-sdk/react，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（^19\.0\.0）、react-dom（^19\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @a2ui-sdk/react 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @a2ui-sdk/react 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @a2ui-sdk/react 可以商用吗？

@a2ui-sdk/react 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @a2ui-sdk/react 的下载量有多少？

根据 npm 官方下载统计，@a2ui-sdk/react 在 2026/10/05 – 2026/11/03 这 30 天内被下载 9,799 次，日均约 327 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @a2ui-sdk/react 还在维护吗？

最新版本 0\.4\.0 发布于 2026/02/02（9 个月前）；至今共发布 11 个版本，其中过去 12 个月发布了 11 个；首次发布于 2026/01/13。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

