目录
1. ReactLive 是什么?能做什么?
2. ReactLive 的构成?工作原理?
3. 综合示例
1. ReactLive 是什么?能做什么?
React Live 能实现 React 组件级的在线编辑、预览功能。
-
React Live brings you the ability to render React components with editable source code and live preview.
import { LiveProvider, LiveEditor, LiveError, LivePreview } from 'react-live'
2. ReactLive 的构成?工作原理?
-
核心构成
-
buble:轻量级 ES2015 语法转换器
-
The blazing fast, batteries-included ES2015 compiler.
-
react-simple-code-editor:代码展示
-
A simple no-frills code editor with syntax highlighting.
-
prism-react-renderer:代码高亮
-
A lean Prism highlighter component for React
-
核心原理
-
从下面的代码可以看出,代码片段中的依赖,都需要外部注入:
-
React 会被默认注入;
-
scope 中定制的内容也会被注入;
3. 综合示例
-
支持 echarts
-
支持 Hook:useEffect、useState、useRef
import React, { useState, useEffect, useRef } from "react";
import * as echarts from "echarts";
import { LiveProvider, LiveEditor, LiveError, LivePreview } from "react-live";
import dracula from "prism-react-renderer/themes/dracula";
interface ReactEditorProps {
code: string;
onChange?: (code: string) => void;
codeProps?: object;
showEditor?: boolean;
}
export default function ReactEditor(props: ReactEditorProps) {
const { code, onChange, codeProps = {}, showEditor = true } = props;
const scope = { useState, useEffect, useRef, echarts, props: codeProps };
const transformCode = (code: string) => {
const regex = /\(.*?\)\s*=>/;
const removedArgumentProps = code.replace(regex, "() => ");
return removedArgumentProps;
};
return (
<LiveProvider
code={code}
scope={scope}
transformCode={transformCode}
theme={dracula}
>
<div style={{ display: "flex" }}>
<div style={{flex: "1 1 0px"}}>
<LivePreview />
</div>
{showEditor && (
<div style={{flex: "1 1 0px"}}>
<LiveEditor onChange={onChange} />
</div>
)}
</div>
<LiveError />
</LiveProvider>
);
}
参考:
ReactLive:
react-simple-code-editor:
prism-react-renderer:
buble: