Skip to content

接入渲染器

接入编辑器之后,通过页面编辑,最终倒出后可以得到一个页面的 schema json 协议,如何将协议重新渲染为一个可以运行的 React 页面呢?

安装

shell npm i @chamn/render

如果已经安装过则不需要安装。

用法

render.tsx
import React from 'react';
import { useEffect, useState } from 'react';
import { ReactAdapter, Render, useRender, AssetLoader, collectVariable, flatObject } from '@chamn/render';
import { AssetPackage, CPageDataType } from '@chamn/model';
const loadAssets = async (assets: AssetPackage[]) => {
// 注入组件物料资源
const assetLoader = new AssetLoader(assets);
try {
await assetLoader.load();
// 从子窗口获取物料对象
const componentCollection = collectVariable(assets, window);
const components = flatObject(componentCollection);
return components;
} catch (e) {
return null;
}
};
export const Preview = () => {
const [page, setPage] = useState<CPageDataType>();
const renderHandle = useRender();
const [loading, setLoading] = useState(true);
const [pageComponents, setPageComponents] = useState({});
const loadPageAssets = async (assets: AssetPackage[]) => {
const components = await loadAssets(assets);
if (components) {
setPageComponents(components);
setLoading(false);
}
};
useEffect(() => {
const localPage = localStorage.getItem('pageSchema');
if (localPage) {
const page: CPageDataType = JSON.parse(localPage);
setPage(page);
loadPageAssets(page.assets || []);
}
}, []);
if (loading) {
return <>Not find page info on local, please ensure you save it on editor</>;
}
return (
<div className="App" style={{ overflow: 'auto', height: '100%' }}>
<Render
page={page}
components={{
...pageComponents,
}}
render={renderHandle}
adapter={ReactAdapter}
/>
</div>
);
};

如果你在页面中用了一些第三方组件,比如 antd, 你需要手动的 improt 相关库,并将其拍平后传递给 components 属性

Example:

import * as Antd from 'antd';
import * as CustomComponents from 'xxx';
// 每个 key 都是组件名需要唯一,value 表示对应的运行时组件
const components: Record<string, any> = {
...Antd,
...CustomComponents,
};