使用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)
  )
}
相关推荐
Heo1 小时前
深入React19任务调度器Scheduler
前端·javascript·面试
boooooooom1 小时前
Vue3 nextTick 实现大变化:微任务优先,彻底搞懂渲染时机!
javascript·vue.js·面试
用户14436183400971 小时前
你不知道的JS上-(九)
前端·javascript
不会敲代码12 小时前
从原子CSS到TailwindCSS:现代前端样式解决方案全解析
前端·css·react.js
冴羽2 小时前
2026 年 JavaScript 框架 3 大趋势
前端·javascript·react.js
思茂信息2 小时前
基于CST 3D Combined功能的以太网口RE仿真
开发语言·javascript·单片机·嵌入式硬件·matlab·3d
一拳不是超人3 小时前
从“必选项”到“性能包袱”:为什么现代框架开始“抛弃”虚拟 DOM?
前端·javascript·架构
Gogo11214 小时前
JavaScript 里的“空”:Null 与 Undefined 的终极指南
javascript
用户6802659051194 小时前
全栈可观测性白皮书——实施、收益与投资回报率
javascript·后端·面试
掘金安东尼5 小时前
⏰前端周刊第 454 期(2026年2月16日-2月22日)
前端·javascript·面试