使用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)
  )
}
相关推荐
摘星编程28 分钟前
React Native鸿蒙:Calendar日程标记显示
react native·react.js·harmonyos
phltxy2 小时前
Vue3入门指南:从环境搭建到数据响应式,开启高效前端开发之旅
前端·javascript·vue.js
电商API&Tina2 小时前
乐天平台 (Rakuten) 数据采集指南
大数据·开发语言·数据库·oracle·json
摘星编程3 小时前
OpenHarmony + RN:ProgressBar进度条组件
javascript·react native·react.js
冰暮流星3 小时前
javascript之双重循环
开发语言·前端·javascript
爱敲点代码的小哥3 小时前
C#视觉模板匹配与动态绘制实战(绘制和保存,加载tb块,处理vpp脚本的方式)
前端·javascript·信息可视化
南风知我意9573 小时前
【前端面试3】初中级难度
前端·javascript·面试
霍理迪3 小时前
JS作用域与预解析
开发语言·前端·javascript
蓉妹妹4 小时前
在React中使用Scroll嵌套Scroll,出现里面Scroll滚动条超出高度却滚动没反应的问题,解决方案添加nestedScrollEnabled
javascript·react native·react.js
rosmis4 小时前
地铁病害检测系统软件改进记录-2-02
开发语言·前端·javascript