使用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)
  )
}
相关推荐
紫金修道1 分钟前
【OpenClaw】让openclaw根据需求创造自定义skill记录
前端·javascript·chrome
嘉琪0019 分钟前
Day6 完整学习包(async/await)——2026 0318
前端·javascript·学习
css趣多多17 分钟前
# Vue 3 `<script setup>` 中变量声明的正确姿势:何时必须使用 `ref()`?
前端·javascript·vue.js
凌晨一点的秃头猪23 分钟前
Python JSON 模块核心函数超详细指南
json
kyriewen1130 分钟前
Sass:让 CSS 从手工作坊迈入工业时代
前端·javascript·css·html·css3·sass·html5
冰暮流星31 分钟前
javascript之变量作用域
开发语言·前端·javascript
lxh011335 分钟前
嵌套数组生成器题解
开发语言·javascript·ecmascript
Dxy123931021639 分钟前
DrissionPage使用js点击:突破常规交互限制的“隐形手”
开发语言·javascript·交互
北寻北爱1 小时前
面试题-js篇
前端·javascript
这是个栗子1 小时前
前端开发中的常用工具函数(五)
javascript·数据结构·reduce