使用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)
  )
}
相关推荐
狗头大军之江苏分军1 小时前
《潮水漫过十七岁》倒计时
前端·javascript·后端
小码哥0682 小时前
租房平台源码部署验收:房源样例、区域字典与看房预约逐项验证
前端·javascript·vue.js·租房小程序·租房系统·租房软件
htzyl2063 小时前
JS原型链与继承:class 底下到底是什么
前端·javascript·ecmascript 6
htzyl2063 小时前
JS-关于闭包捕获与释放
前端·javascript
狗头大军之江苏分军3 小时前
《潮水漫过十七岁》好久没写了
前端·javascript·后端
蔓越莓曲奇6 小时前
给 DeepSeek Harness 换上 GTA 6 皮肤:Agent 一干活,通缉星级就亮
前端·javascript·开源
KevinWang_6 小时前
iOS 开发计划(四) - 拆分模块
javascript
1-1=010 小时前
Vue 全局事件总线
前端·javascript·vue.js
AI前端工程狮11 小时前
我给 MCP 工具加了删除确认,用户点了拒绝,数据还是删了
javascript·人工智能·程序员
niyongsheng11 小时前
CopyCraft 字帖工坊:React + Electron 做一个全平台本地字帖生成器
react.js·electron·开源