> ## Documentation Index
> Fetch the complete documentation index at: https://omer-914cc1c6.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 可复用片段

> 复用自定义片段，保持内容一致

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

<div id="creating-a-custom-snippet">
  ## 创建自定义片段
</div>

**前置条件**：必须在 `snippets` 目录中创建片段文件，导入才能生效。

`snippets` 目录中的任何页面都会被视为片段，不会被渲染为独立页面。若要基于该片段创建独立页面，请将其导入到另一个文件中，并以组件形式调用。

<div id="default-export">
  ### 默认导出
</div>

1. 将你希望复用的内容添加到片段文件中。你也可以添加变量，在导入片段时通过 props 进行填充。在此示例中，我们的变量是 word。

```typescript snippets/my-snippet.mdx theme={null}
你好世界！这是我想要在各个页面中重复使用的内容。 
```

2. 将该代码片段导入到目标文件中。

```typescript destination-file.mdx theme={null}
---
title: 我的标题
description: 我的说明
---

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

## 标题

Lorem ipsum dolor sit amet.

<MySnippet/>

```

<div id="exporting-with-variables">
  ### 使用变量导出
</div>

1. 你也可以选择添加一些变量，在导入该片段时通过 props 传入并填充。在本示例中，我们的变量是 word。

```typescript snippets/my-snippet.mdx theme={null}
我今天的关键词是 {word}。
```

2. 在目标文件中使用该变量导入代码片段。该属性会根据你的设定自动填充。

```typescript destination-file.mdx theme={null}
---
title: 我的标题
description: 我的说明
---

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

## 标题

Lorem ipsum dolor sit amet.

<MySnippet word="bananas" />

```

<div id="reusable-variables">
  ### 可重用变量
</div>

1. 从你的代码片段（snippet）文件中导出一个变量：

```typescript snippets/path/to/custom-variables.mdx theme={null}
export const myName = '我的名字';

export const myObject = { fruit: '草莓' };
```

2. 从目标文件导入该代码片段，并使用该变量：

```typescript destination-file.mdx theme={null}
---
title: 我的标题
description: 我的说明
---

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

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

<div id="jsx-snippets">
  ### JSX 片段
</div>

1. 从片段文件中导出一个 JSX 组件。（参见[React 组件](/zh/react-components)了解更多信息）：

```js icon=square-js snippets/my-jsx-snippet.jsx theme={null}
export const MyJSXSnippet = () => {
  return (
    <div>
      <h1>你好，世界！</h1>
    </div>
  )
}
```

<Note>
  重要：创建 JSX 代码片段时，请使用箭头函数语法（`=>`），不要使用函数声明。在此 context 中不支持 `function` 关键字。
</Note>

2. 从目标文件中导入该片段，并使用该组件：

```typescript destination-file.mdx theme={null}
---
title: 我的标题
description: 我的说明
---

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

<MyJSXSnippet />
```
