用于 json-render 的 React 渲染器,将 JSON 规范转换为 React 组件。当使用 @json-render/react、从 JSON 构建 React UI、创建组件目录或渲染 AI 生成的规范时使用。
@json-render/react
将 JSON 规范转换为 React 组件树的 React 渲染器。
快速开始
import { defineRegistry, Renderer } from "@json-render/react";
import { catalog } from "./catalog";
const { registry } = defineRegistry(catalog, {
components: {
Card: ({ props, children }) => <div>{props.title}{children}</div>,
},
});
function App({ spec }) {
return <Renderer spec={spec} registry={registry} />;
}
创建目录
import { defineCatalog } from "@json-render/core";
import { schema } from "@json-render/react/schema";
import { defineRegistry } from "@json-render/react";
import { z } from "zod";
// 创建带有 props 模式的目录
export const catalog = defineCatalog(schema, {
components: {
Button: {
props: z.object({
label: z.string(),
variant: z.enum(["primary", "secondary"]).nullable(),
}),
description: "可点击的按钮",
},
Card: {
props: z.object({ title: z.string() }),
description: "带有标题的卡片容器",
},
},
});
// 定义类型安全的组件实现
const { registry } = defineRegistry(catalog, {
components: {
Button: ({ props }) => (
<button className={props.variant}>{props.label}</button>
),
Card: ({ props, children }) => (
<div className="card">
<h2>{props.title}</h2>
{children}
</div>
),
},
});
规范结构(元素树)
React 模式使用元素树格式:
{
"root": {
"type": "Card",
"props": { "title": "Hello" },
"children": [
{ "type": "Button", "props": { "label": "Click me" } }
]
}
}
可见性条件
在元素上使用 visible 根据状态显示/隐藏。新语法:{ "$state": "/path" }、{ "$state": "/path", "eq": value }、{ "$state": "/path", "not": true }、{ "$and": [cond1, cond2] } 用于 AND、{ "$or": [cond1, cond2] } 用于 OR。辅助函数:visibility.when("/path")、visibility.unless("/path")、visibility.eq("/path", val)、visibility.and(cond1, cond2)、visibility.or(cond1, cond2)。
提供者
| 提供者 | 用途 |
|---|---|
StateProvider |
在组件间共享状态(JSON Pointer 路径)。接受可选的 store prop 用于受控模式。 |
ActionProvider |
处理通过事件系统分发的动作 |
VisibilityProvider |
启用基于状态的条件渲染 |
ValidationProvider |
表单字段验证 |
外部存储(受控模式)
将 StateStore 传递给 StateProvider(或 JSONUIProvider / createRenderer)以使用外部状态管理(Redux、Zustand、XState 等):
import { createStateStore, type StateStore } from "@json-render/react";
const store = createStateStore({ count: 0 });
<StateProvider store={store}>{children}</StateProvider>
// 从任何地方修改——React 自动重新渲染:
store.set("/count", 1);
当提供了 store 时,initialState 和 onStateChange 将被忽略。
动态 Prop 表达式
任何 prop 值都可以是数据驱动的表达式,由渲染器在组件接收 props 之前解析:
{ "$state": "/state/key" }- 从状态模型读取(单向读取){ "$bindState": "/path" }- 双向绑定:从状态读取并允许写回。用于表单组件的自然值 prop(value、checked、pressed 等)。{ "$bindItem": "field" }- 双向绑定到重复项字段。在重复作用域内使用。- 过滤列表:在同一容器上使用
repeat加上$item可见条件,仅渲染匹配的项:{ "repeat": { "statePath": "/tasks", "key": "id" }, "visible": { "$item": "status", "eq": "todo" }, "children": ["task-card"] }。AND 组合的$state条件控制容器外壳;$item/$index条件过滤项。 { "$cond": <condition>, "$then": <value>, "$else": <value> }- 条件值{ "$template": "Hello, ${/name}!" }- 将状态值插值到字符串中{ "$computed": "fn", "args": { ... } }- 调用已注册的函数,参数已解析
{
"type": "Input",
"props": {
"value": { "$bindState": "/form/email" },
"placeholder": "Email"
}
}
组件不使用 statePath prop 进行双向绑定。请改用 { "$bindState": "/path" } 放在自然值 prop 上。
组件接收已解析的 props。对于双向绑定的 props,使用 useBoundProp 钩子,配合渲染器提供的 bindings 映射。
通过 JSONUIProvider 或 createRenderer 的 functions prop 注册 $computed 函数:
<JSONUIProvider
functions={{ fullName: (args) => `${args.first} ${args.last}` }}
>
事件系统
组件使用 emit 触发命名事件,或使用 on() 获取带有元数据的事件句柄。元素的 on 字段将事件映射到动作绑定:
// 简单事件触发
Button: ({ props, emit }) => (
<button onClick={() => emit("press")}>{props.label}</button>
),
// 带有元数据的事件句柄(例如 preventDefault)
Link: ({ props, on }) => {
const click = on("click");
return (
<a href={props.href} onClick={(e) => {
if (click.shouldPreventDefault) e.preventDefault();
click.emit();
}}>{props.label}</a>
);
},
{
"type": "Button",
"props": { "label": "Submit" },
"on": { "press": { "action": "submit" } }
}
on() 返回的 EventHandle 具有:emit()、shouldPreventDefault(布尔值)和 bound(布尔值)。
状态监听器
元素可以声明 watch 字段(顶级,与 type/props/children 同级),以在状态值变化时触发动作:
{
"type": "Select",
"props": { "value": { "$bindState": "/form/country" }, "options": ["US", "Canada"] },
"watch": { "/form/country": { "action": "loadCities" } },
"children": []
}
内置动作
setState、pushState、removeState 和 validateForm 动作内置于 React 模式中,由 ActionProvider 自动处理。它们被注入到 AI 提示中,无需在目录的 actions 中声明:
{ "action": "setState", "params": { "statePath": "/activeTab", "value": "home" } }
{ "action": "pushState", "params": { "statePath": "/items", "value": { "text": "New" } } }
{ "action": "removeState", "params": { "statePath": "/items", "index": 0 } }
{ "action": "validateForm", "params": { "statePath": "/formResult" } }
validateForm 验证所有已注册的字段,并将 { valid, errors } 写入状态。
注意:动作参数中的 statePath(例如 setState.statePath)指向突变路径。组件 props 中的双向绑定使用 { "$bindState": "/path" } 放在值 prop 上,而不是 statePath。
useBoundProp
对于需要双向绑定的表单组件,当 prop 使用 { "$bindState": "/path" } 或 { "$bindItem": "field" } 时,使用 useBoundProp 配合渲染器提供的 bindings 映射:
import { useBoundProp } from "@json-render/react";
Input: ({ element, bindings }) => {
const [value, setValue] = useBoundProp<string>(
element.props.value,
bindings?.value
);
return (
<input
value={value ?? ""}
onChange={(e) => setValue(e.target.value)}
/>
);
},
useBoundProp(propValue, bindingPath) 返回 [value, setValue]。value 是解析后的 prop;setValue 写回到绑定的状态路径(如果未绑定则为空操作)。
BaseComponentProps
用于构建不绑定到特定目录的可复用组件库(例如 @json-render/shadcn):
import type { BaseComponentProps } from "@json-render/react";
const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) => (
<div>{props.title}{children}</div>
);
defineRegistry
defineRegistry 仅在目录声明了动作时才有条件地要求 actions 字段。带有 actions: {} 的目录可以省略它。
关键导出
| 导出 | 用途 |
|---|---|
defineRegistry |
从目录创建类型安全的组件注册表 |
Renderer |
使用注册表渲染规范 |
schema |
元素树模式(包含内置状态动作:setState、pushState、removeState、validateForm) |
useStateStore |
访问状态上下文 |
useStateValue |
从状态获取单个值 |
useBoundProp |
用于 $bindState/$bindItem 表达式的双向绑定 |
useActions |
访问动作上下文 |
useAction |
获取单个动作分发函数 |
useOptionalValidation |
useValidation 的非抛出变体(如果没有提供者则返回 null) |
useUIStream |
从 API 端点流式传输规范 |
createStateStore |
创建框架无关的内存 StateStore |
StateStore |
用于插入外部状态管理的接口 |
BaseComponentProps |
用于可复用组件库的目录无关基础类型 |
EventHandle |
事件句柄类型(emit、shouldPreventDefault、bound) |
ComponentContext |
类型化的组件上下文(目录感知) |






