使用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)
  )
}
相关推荐
用户479492835691520 小时前
React DevTools 组件名乱码?揭秘从开发到生产的代码变形记
前端·react.js
菜鸟‍21 小时前
【前端学习】阿里前端面试题
前端·javascript·学习
用户479492835691521 小时前
告别span嵌套地狱:CSS Highlights API重新定义语法高亮
前端·javascript·css
眠りたいです21 小时前
基于脚手架微服务的视频点播系统-客户端业务逻辑处理部分(三)-客户端主体部分完结
c++·微服务·云原生·架构·json·restful·qt6.7
九章云极AladdinEdu1 天前
项目分享|告别枯燥命令行,构建终端用户界面的 TypeScript 库
javascript·ui·typescript
带着梦想扬帆启航1 天前
UniApp 多个异步开关控制教程
前端·javascript·uni-app
小高0071 天前
JavaScript 内存管理是如何工作的?
前端·javascript
是大林的林吖1 天前
解决 elementui el-cascader组件懒加载时存在选中状态丢失的问题?
前端·javascript·elementui
默 语1 天前
Electron 应用中的系统检测方案对比与鸿蒙适配实践
javascript·electron·harmonyos·gwo