代码拉取完成,页面将自动刷新
react-schema-render
是一个通用型 schema 转 React 组件的工具组件。其遵守 Schema To React 规范。
第 1 步:安装
yarn add react-schema-render # npm install react-schema-render -S
第 2 步:建立组件映射关系
我们以 ant-design
的 carousel 作为示例(只是为了好看,其和具体的 UI 库无关)。
# yarn add antd
import { Collapse } from 'antd';
const { Panel } = Collapse;
const components = {
collapse: Collapse,
panel: Panel,
};
第 3 步:传递映射关系
import { setComponents } from 'react-schema-render';
setComponents(components);
第 4 步:定义 schema
const schema = {
// component 代表组件
component: 'collapse',
// 其他属性为 component 对应的属性
defaultActiveKey: ['1'],
// children 支持深度嵌套
children: [
{
component: 'panel',
header: '《出塞》',
key: '1',
// children 为字符串
children:
'秦时明月汉时关,万里长征人未还。但使龙城飞将在,不教胡马度阴山。',
},
{
component: 'panel',
header: '《寻隐者不遇》',
key: '2',
// children 为 jsx
children: (
<>
<p>松下问童子,言师采药去。</p>
<p>只在此山中,云深不知处。</p>
</>
),
},
{
component: 'panel',
header: '《凉州词》',
key: '3',
// children 为 schema 数组
children: [
{
component: 'p',
key: 1,
children: '葡萄美酒夜光杯,欲饮琵琶马上催。',
},
{
component: 'p',
key: 2,
children: '醉卧沙场君莫笑,古来征战几人回?',
},
],
},
],
};
第 5 步:使用
import { SchemaRender } from 'react-schema-render';
<SchemaRender schema={schema}></SchemaRender>;
完成 Demo:
import React from 'react';
import { Collapse } from 'antd';
import { setComponents, SchemaRender } from 'react-schema-render';
const { Panel } = Collapse;
const components = {
collapse: Collapse,
panel: Panel,
};
setComponents(components);
const App = () => {
const schema = {
component: 'collapse',
defaultActiveKey: ['1'],
children: [
{
component: 'panel',
header: '《出塞》',
key: '1',
// children 为字符串
children:
'秦时明月汉时关,万里长征人未还。但使龙城飞将在,不教胡马度阴山。',
},
{
component: 'panel',
header: '《寻隐者不遇》',
key: '2',
// children 为 jsx
children: (
<>
<p>松下问童子,言师采药去。</p>
<p>只在此山中,云深不知处。</p>
</>
),
},
{
component: 'panel',
header: '《凉州词》',
key: '3',
// children 为 schema 数组
children: [
{
component: 'p',
key: 1,
children: '葡萄美酒夜光杯,欲饮琵琶马上催。',
},
{
component: 'p',
key: 2,
children: '醉卧沙场君莫笑,古来征战几人回?',
},
],
},
],
};
return <SchemaRender schema={schema}></SchemaRender>;
};
export default App;
更多功能演示和 API 说明,请参见文档:
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
1. 开源生态
2. 协作、人、软件
3. 评估模型