使用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)
  )
}
相关推荐
好奇心笔记10 分钟前
ai写代码随机拉大的,所以我准备给AI出一个设计规范
前端·javascript
江城开朗的豌豆10 分钟前
Vue状态管理进阶:数据到底是怎么"跑"的?
前端·javascript·vue.js
我想说一句13 分钟前
React待办事项开发记:Hook魔法与组件间的悄悄话
前端·javascript·前端框架
真夜14 分钟前
CommonJS与ESM
前端·javascript
G等你下课16 分钟前
从点击到执行:如何优雅地控制高频事件触发频率
前端·javascript·面试
Jackson_Mseven16 分钟前
面试官:说说 startTransition 和 useDeferredValue?我:我用它一行代码救了首页!
前端·javascript·面试
架构个驾驾16 分钟前
从0到1搭建Vue3+Vant移动端项目(一)
前端·javascript·vue.js
然我17 分钟前
React 中 useEffect 到底怎么用才不会踩坑?全流程详解 + 实例讲透副作用
前端·javascript·react.js
前端付豪17 分钟前
12、表单系统设计:动态表单 + 校验 + 可配置化
前端·javascript·架构
sophister18 分钟前
你以为的 2025-05-28,其实是另一天:JavaScript 日期解析那些坑与最佳实践
前端·javascript