跳转到主要内容
软件开发的核心原则之一是 DRY(Don’t Repeat Yourself,不要重复),这同样适用于文档。如果你发现在多个位置重复相同的内容,应该创建自定义片段以保持内容一致。

创建自定义片段

前置条件:必须在 snippets 目录中创建片段文件,导入才能生效。 snippets 目录中的任何页面都会被视为片段,不会被渲染为独立页面。若要基于该片段创建独立页面,请将其导入到另一个文件中,并以组件形式调用。

默认导出

  1. 将你希望复用的内容添加到片段文件中。你也可以添加变量,在导入片段时通过 props 进行填充。在此示例中,我们的变量是 word。
snippets/my-snippet.mdx
你好世界这是我想要在各个页面中重复使用的内容
  1. 将该代码片段导入到目标文件中。
destination-file.mdx
---
title: 我的标题
description: 我的说明
---

import MySnippet from '/snippets/path/to/my-snippet.mdx';

## 标题

Lorem ipsum dolor sit amet.

<MySnippet/>

使用变量导出

  1. 你也可以选择添加一些变量,在导入该片段时通过 props 传入并填充。在本示例中,我们的变量是 word。
snippets/my-snippet.mdx
我今天的关键词是 {word}。
  1. 在目标文件中使用该变量导入代码片段。该属性会根据你的设定自动填充。
destination-file.mdx
---
title: 我的标题
description: 我的说明
---

import MySnippet from '/snippets/path/to/my-snippet.mdx';

## 标题

Lorem ipsum dolor sit amet.

<MySnippet word="bananas" />

可重用变量

  1. 从你的代码片段(snippet)文件中导出一个变量:
snippets/path/to/custom-variables.mdx
export const myName = '我的名字';

export const myObject = { fruit: '草莓' };
  1. 从目标文件导入该代码片段,并使用该变量:
destination-file.mdx
---
title: 我的标题
description: 我的说明
---

import { myName, myObject } from '/snippets/path/to/custom-variables.mdx';

你好我的名字是 {myName},我喜欢 {myObject.fruit}。

JSX 片段

  1. 从片段文件中导出一个 JSX 组件。(参见React 组件了解更多信息):
snippets/my-jsx-snippet.jsx
export const MyJSXSnippet = () => {
  return (
    <div>
      <h1>你好,世界!</h1>
    </div>
  )
}
重要:创建 JSX 代码片段时,请使用箭头函数语法(=>),不要使用函数声明。在此 context 中不支持 function 关键字。
  1. 从目标文件中导入该片段,并使用该组件:
destination-file.mdx
---
title: 我的标题
description: 我的说明
---

import { MyJSXSnippet } from '/snippets/my-jsx-snippet.jsx';

<MyJSXSnippet />
I