使用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 分钟前
智能前端新纪元:语音交互技术与安全实践全解析
javascript
1234Wu29 分钟前
React Native 接入 eCharts
javascript·react native·react.js
脑袋大大的8 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
速易达网络9 小时前
RuoYi、Vue CLI 和 uni-app 结合构建跨端全家桶方案
javascript·vue.js·低代码
耶啵奶膘9 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
JoJo_Way9 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
视频砖家10 小时前
移动端Html5播放器按钮变小的问题解决方法
前端·javascript·viewport功能
小白变怪兽12 小时前
一、react18+项目初始化(vite)
前端·react.js
葬歌倾城12 小时前
JSON的缩进格式方式和紧凑格式方式
c#·json