使用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)
  )
}
相关推荐
凌晨三点说晚安4 小时前
理解 JavaScript 作用域链、return 与闭包
javascript
tryCbest4 小时前
Vue系列——第 20 篇:Vue Router 4——路由管理完全指南(上)
前端·javascript·vue.js
feixing_fx4 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
Funlang5 小时前
在 Windows 95 上写前端
前端·javascript·windows
AI前端工程狮5 小时前
我给 MCP 长任务加进度条,五步只显示了一步
javascript·人工智能·程序员
彩虹暴龙兽8 小时前
JavaScript 作用域、闭包与对象
javascript
Highcharts.js8 小时前
Highcharts与TypeScript集成指南
前端·javascript·typescript·前端框架·数据可视化·highcharts
桃李无言下自成蹊9 小时前
为什么越清晰的二维码越扫不出来:jsQR 四轮解码与 8 个真实坑
javascript
小y的笔记10 小时前
Vue 3 异步搜索实战:watch、请求取消与竞态控制
前端·javascript
用户2986985301412 小时前
React 前端实现 Excel 与 HTML 双向转换:基于 WebAssembly 的浏览器端方案
javascript·html·excel