使用React将JSON渲染为组件

使用React将JSON 渲染为组件

实现思路

要将JSON Schema渲染为React组件,我们可以按照以下步骤进行实现:

  1. 得到JSON .

  2. 构建自定义组件 。

  3. 嵌套渲染功能实现 。

示例代码
typescript 复制代码
import React, { useState, useEffect } from "react";

interface Schema {
  type: string;
  title?: string;
  content?: string;
  props?: object;
  children?: Schema[];
}
interface CardSchema extends Schema {
  title: string;
  content: string;
}
// 卡片组件
function Card({ schema }: { schema: CardSchema }) {
  return (
    <div className="card">
      <h2>{schema.title}</h2>
      <p>{schema.content}</p>
    </div>
  );
}
// 容器组件,支持嵌套
function Container({ schema, renderSchema }: { schema: Schema, renderSchema: (schema: Schema) => JSX.Element }) {
  return (
    <div className="container">
      {schema?.children?.map(renderSchema)}
    </div>
  );
}
// 原生组件
function DynamicElement({ schema, renderSchema }: { schema: Schema, renderSchema: (schema: Schema) => JSX.Element }) {
  const children = schema?.children?.map(renderSchema)
  const type = schema.type;
  const props = schema.props;
  if (type === 'input') {
    return <input {...props} />
  } else {
    return React.createElement(type, props, children);
  }
}
//渲染核心组件
function renderSchema(schema: Schema): JSX.Element {
  switch (schema.type) {
    case 'card':
      return <Card schema={schema as CardSchema} />;
    case 'container':
      return <Container schema={schema} renderSchema={renderSchema} />;
    default:
      return <DynamicElement schema={schema} renderSchema={renderSchema} />;
  }
}

const schemaTmp = { type: 'container', children: [{ type: 'card', title: '标题', content: '内容' }, { type: 'card', title: '标题', content: '内容' }, { type: 'card', title: '标题', content: '内容' }, { type: 'div', props: {}, children: [{ type: 'input', props: { value: '111' }, children: [] }] }] }

export default function Home() {
  return (
    renderSchema(schemaTmp)
  )
}
相关推荐
默_笙5 分钟前
🚅 地铁的"回头路、存档点与人工闸机"(下):LangGraph 的循环、持久化与中断
前端·javascript
flash俊杰12 分钟前
Zod Schema 驱动的 IPC 契约:从入参校验到状态机一致性的三层防御
javascript·typescript
一条溺水的鱼2 小时前
一次讲透 JS 原型链 —— prototype、__proto__ 和 constructor 到底啥关系
javascript
三乐2283 小时前
一文搞懂 JS 事件流:捕获、冒泡、事件委托
javascript·html
databook3 小时前
DuckDB + SQL 高效分析 JSON 数据
数据分析·json·nosql
愛芳芳5 小时前
基于 Electron + Vue3 的仿 PC 微信客户端项目实战
前端·javascript·css·elementui·typescript·electron·vue
阿虎儿6 小时前
论 JavaScript 的怪异之处
javascript
gnip6 小时前
uts 插件示例:获取设备电量信息
前端·javascript
gnip7 小时前
uni-app 原生插件
前端·javascript·uni-app
gnip7 小时前
跨域常用解决方案
前端·javascript