使用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)
  )
}
相关推荐
Icoolkj3 分钟前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
^Rocky1 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
西陵2 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
笑鸿的学习笔记2 小时前
JavaScript笔记之JS 和 HTML5 的关系
javascript·笔记·html5
萌萌哒草头将军3 小时前
10个 ES2025 新特性速览!🚀🚀🚀
前端·javascript·vue.js
gnip4 小时前
http缓存
前端·javascript
敬业小码哥4 小时前
记一次:mysql的json及json数组使用组合使用
数据库·mysql·json
一键三联啊4 小时前
BSON 和 JSON 的区别
json
JohnYan5 小时前
工作笔记 - 微信消息发送和处理
javascript·后端·微信
陈陈爱java6 小时前
Spring八股文
开发语言·javascript·数据库