使用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)
  )
}
相关推荐
SHIPKING39329 分钟前
【HTML】个人博客页面
javascript·css·html
junjun.chen06062 小时前
【在qiankun模式下el-dropdown点击,浏览器报Failed to execute ‘getComputedStyle‘ on ‘Window‘: parameter 1 is not o
前端·javascript·前端框架
課代表2 小时前
AcroForm JavaScript Promise 对象应用示例: 异步加载PDF文件
开发语言·javascript·pdf·promise·对象
zm2 小时前
服务器连接多客户端
java·javascript·算法
小屁孩大帅-杨一凡3 小时前
一个简单点的js的h5页面实现地铁快跑的小游戏
开发语言·前端·javascript·css·html
bing_1584 小时前
Spring MVC 根据请求头 (如 Accept) 怎么返回 JSON 或 XML 数据?
spring·json·mvc
purpleseashell_Lili4 小时前
配置别名路径 @
javascript·react
这个一个非常哈5 小时前
VUE篇之自定义组件使用v-model
前端·javascript·vue.js
热爱前端的小君同学5 小时前
长按拖拽移动的vue3组件
前端·javascript·vue.js
Coding的叶子5 小时前
Node.js 安装 + React Flow 快速入门:环境安装与项目搭建
react.js·node.js·react flow·fgai·react agent