使用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)
  )
}
相关推荐
狗狗摇屁屁23 分钟前
JS手写防抖
开发语言·javascript·ecmascript
清风细雨_林木木32 分钟前
Chart.js和 Echart的区别
开发语言·javascript·ecmascript
沐泽__1 小时前
iframe内嵌页面双向通信
前端·javascript·chrome
小北方城市网1 小时前
第4 课:Vue 3 路由与状态管理实战 —— 从单页面到多页面应用
前端·javascript·vue.js
interception1 小时前
爬虫逆向,瑞数6,补环境,国家专利
javascript·爬虫·python·网络爬虫
掘金安东尼2 小时前
顶层元素问题:popover vs. dialog
前端·javascript·面试
掘金安东尼2 小时前
React 的新时代已经到来:你需要知道的一切
前端·javascript·面试
1024肥宅2 小时前
现代 JavaScript 特性:TypeScript 深度解析与实践
前端·javascript·typescript
CC码码3 小时前
告别杂乱数字:用 Intl.NumberFormat 打造全球友好的前端体验
前端·javascript·面试
kandee3 小时前
vscode混淆js文件的插件用法(jshaman)
javascript·ide·vscode