使用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)
  )
}
相关推荐
颜酱2 小时前
Dijkstra 算法:从 BFS 到带权最短路径
javascript·后端·算法
从文处安3 小时前
「前端何去何从」一直写 Vue ,为何要在 AI 时代去学 React?
前端·react.js
yuki_uix3 小时前
重新认识 React Hooks:从会用到理解设计
前端·react.js
想努力找到前端实习的呆呆鸟4 小时前
网易云桌面端--精选歌单布局思路记录
前端·javascript·vue.js
进击的尘埃7 小时前
策略模式和状态模式到底啥区别?拿审批流表单说个明白
javascript
专业抄代码选手7 小时前
在react中,TSX是如何转变成JS的
前端·javascript
进击的尘埃8 小时前
SOLID 原则在 React 组件库里怎么落地:五个重构案例
javascript
本末倒置1838 小时前
Bun 内置模块全解析:告别第三方依赖,提升开发效率
前端·javascript·node.js
进击的尘埃8 小时前
中介者模式:把面板之间的蜘蛛网拆干净
javascript
Hilaku8 小时前
OpenClaw 很爆火,但没人敢聊它的权限安全🤷‍♂️
前端·javascript·程序员