React Live in Docusaurus
React Live 可用于在页面上实时编辑代码并展示,下面以 Docusaurus 的交互式代码编辑器为例。
一、交互式代码编辑器
1、安装与使用
Docusaurus 文档中可以使用交互式代码编辑器在文档中添加实时代码展示。
yarn add @docusaurus/theme-live-codeblock
安装后在 docusaurus.config.js 中的 themes 添加:
module.exports = {
  // ...
  themes: ['@docusaurus/theme-live-codeblock'],
  // ...
};
使用时在文档中的代码块后面加上 live 即可:
function Clock(props) {
  const [date, setDate] = useState(new Date());
  useEffect(() => {
    var timerID = setInterval(() => tick(), 1000);
    return function cleanup() {
      clearInterval(timerID);
    };
  });
  function tick() {
    setDate(new Date());
  }
  return (
    <div>
      <h2>It is {date.toLocaleTimeString()}.</h2>
    </div>
  );
}
效果如下:

2、引入组件
在文档中运行以下命令:
yarn run swizzle @docusaurus/theme-live-codeblock ReactLiveScope
会自动生成 src/theme/ReactLiveScope/index.js 文件:
import React from 'react'
import { Button1 } from 'xx-design'
const Button2 = (props) => (
  <button
    {...props}
  />
)
const ReactLiveScope = {
  React,    // 引入 React
  ...React, // 引入 useState 之类的钩子
  Button1,  // 引入的第三方组件
  Button2,  // 引入的自定义组件
}
export default ReactLiveScope
然而,使用该插件在文档中的代码展示样式是固定的,可以 eject 出来用 ReactLive 自定义交互式代码编辑器插件。
二、定制代码编辑器
在文档中运行以下命令:
yarn swizzle @docusaurus/theme-live-codeblock Playground
会自动生成 src/themes/Playground/index.js 文件,这个文件就是文档中的交互式代码编辑器,可以完全使用 ReactLive 进行定制,首先安装 ReactLive:
yarn add react-live
然后在生成的 Playground/index.js 文件里面使用:
import React from 'react';
// import Playground from '@theme-original/Playground';
import {
  LiveProvider,
  LiveEditor,
  LiveError,
  LivePreview
} from 'react-live'
import oceanicNext from "prism-react-renderer/themes/oceanicNext";
export default function PlaygroundWrapper(props) {
  const {
    children
  } = props
  return (
    <UI.Playground>
      {/* <Playground {...props} /> */}
      <LiveProvider
        code={children.replace(/\n$/, "")}
        theme={oceanicNext}
        {...props}
      >
        <div>
          <LivePreview />
          <LiveError />
        </div>
        <div>
          <LiveEditor />
        </div>
      </LiveProvider>
    </UI.Playground>
  );
}
其中 <LiveProvider> 传入的 theme 属性为代码主题,需要使用 prism-react-renderer,安装如下:
yarn add prism-react-renderer