使用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)
  )
}
相关推荐
光影少年18 分钟前
Redux 中间件作用(redux-thunk/redux-saga)
前端·react.js·掘金·金石计划
爱上好庆祝19 分钟前
学习JS第十一天(JS的进阶)
前端·javascript·学习
喵个咪31 分钟前
统一范式:中后台Admin项目标准化API分层开发方案(Vue/React通用)
前端·vue.js·react.js
UaoN35 分钟前
Vibe Coding 时代,为什么 Tailwind + Shadcn/ui 正在成为现代前端的默认答案
react.js·typescript
kisshyshy1 小时前
# 🔥 数组去重:从双重循环到 Set,面试官想听什么?
javascript·面试
RD_daoyi1 小时前
Google 网站收录全流程解析:抓取、索引与排名机制详解
前端·javascript·人工智能·学习·搜索引擎·html
@大迁世界1 小时前
AI还替不了的JS能力
开发语言·前端·javascript·人工智能·ecmascript
暗冰ཏོ2 小时前
2026前端开发资源整理大全:从基础学习到工程化实战的完整导航
前端·javascript·css·前端框架·html
喵个咪3 小时前
吃透后台权限系统:从架构设计到 Vue3/React 双框架完整落地
前端·vue.js·react.js
HackTwoHub3 小时前
AI赋能Chrome MCP × JS逆向Skill自动化JS逆向挖洞
javascript·人工智能·chrome·安全·web安全·网络安全·自动化