跳到主要内容

Live Code Block

官网支持的代码块组件,基于 react-live,支持实时预览。注意,如果在配置中,markdown.format 配置为 detect,则只能在 .mdx 文档中使用 Live Code Block。

安装

pnpm add @docusaurus/theme-live-codeblock

配置

export default {
plugins: ["@docusaurus/theme-live-codeblock"],
themeConfig: {
liveCodeBlock: {
/**
* The position of the live playground, above or under the editor
* Possible values: "top" | "bottom"
*/
playgroundPosition: "bottom",
},
},
};

使用

在代码片段中添加 live 属性,但是需要注意的是这个只支持 JSX,如果想实时预览其他比如 HTML 代码,需要转化成 JSX。

Hello World

实时编辑器
function HelloWorld() {
  return <div>Hello World</div>;
}
结果
Loading...

noInline 模式

这种模式下,不需要封装成一个函数,但需要在最后自己调用 render 方法。

```js live noInline
const project = 'Docusaurus';

const Greeting = () => <p>Hello {project}!</p>;

render(<Greeting />);

```
实时编辑器
const project = 'Docusaurus';

const Greeting = () => <p>Hello {project}!</p>;

render(<Greeting />);
结果
Loading...

实时预览 HTML 代码

看起来是 HTML,其实是 JSX。

实时编辑器
<div>
  <h1>Hello World</h1>
  <p>这是一个段落</p>
</div>
结果
Loading...

加个颜色和注释,如果用 HTML 的方式会报错

实时编辑器
<div>
  <h1>Hello World</h1>
  <!-- 这是一个注释 -->
  <p style="color: red">这是一个段落</p>
</div>
结果
Loading...

需要使用 JSX 的方式

实时编辑器
<div>
  <h1>Hello World</h1>
  {/* 这是一个注释 */}
  <p style={{color: "red"}}>这是一个段落</p>
</div>
结果
Loading...

渲染 React 组件

实时编辑器
() => {
  const [count, setCount] = useState(0);
  return <div>
    <p>{count}</p>
    <button className="cursor-pointer border p-2 hover:bg-gray-300" onClick={() => setCount(count + 1)}>Click</button>
  </div>;
}
结果
Loading...

如何调用外部的方法

默认环境里只有 React 对象,如果要把其他方法加入到作用域,需要用到 swizzle 技术。

pnpm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope --eject
src/theme/ReactLiveScope/index.js
import React from 'react';

const ButtonExample = (props) => (
<button
{...props}
style={{
backgroundColor: 'white',
color: 'black',
border: 'solid red',
borderRadius: 20,
padding: 10,
cursor: 'pointer',
...props.style,
}}
/>
);

// Add react-live imports you need here
const ReactLiveScope = {
React,
...React,
ButtonExample,
};

export default ReactLiveScope;

The ButtonExample component is now available to use: