mcpField
D
docs-writer-reference

docs-writer-reference

github.com/reactjs开发11.8k70 次安装2 天前更新
代码仓库

关于 docs-writer-reference

面向技术文档作者的 React API 参考页写作技能,提供 Hook、组件、配置、指令、ESLint 规则和 API 索引的模板与规范。

主要功能

  1. 01页面类型决策树
  2. 02六类参考页模板
  3. 03参数与返回值写法
  4. 04注意事项和故障排查规范

适用场景

  1. 01编写 React Hook 参考文档
  2. 02记录编译器选项或指令
  3. 03组织 ESLint 规则文档

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/reactjs/react.dev --skill docs-writer-reference

安装后在 Claude Code 中输入/docs-writer-reference确认已加载。

详细介绍

参考页面撰写指南

快速参考

页面类型决策树
  1. 是 Hook 吗?使用 类型 A(Hook/函数)
  2. 是 React 组件(<Something>)吗?使用 类型 B(组件)
  3. 是编译器配置选项吗?使用 类型 C(配置)
  4. 是指令('use something')吗?使用 类型 D(指令)
  5. 是 ESLint 规则吗?使用 类型 E(ESLint 规则)
  6. 是否列出了多个 API?使用 类型 F(索引/类别)
组件选择

如需选择组件和了解使用模式,请调用 /docs-components。


语气与风格

写作风格: 权威的技术参考文档 语气: 精确、全面、中立

如需了解语气、大小写、术语和行文模式,请调用 /docs-voice。

应该:

  • 以单行描述开篇:“useState 是一个 React Hook,可让你……”
  • 为每个 API 添加参数、返回值和注意事项章节
  • 记录大多数开发者都会遇到的边缘情况
  • 在主要章节之间使用分隔线
  • 添加“在下方查看更多示例”的链接
  • 语气坚定,不要模棱两可——使用“这是专为……设计的”,而不是“这有助于避免……问题”
  • 陈述事实,而不是好处——使用“回调始终访问最新值”,而不是“这有助于避免过时闭包”
  • 使用简洁但有意义的名称——优先使用 onEvent 或 onTick,而不是 onSomething

不应该:

  • 跳过 InlineToc 组件
  • 遗漏错误情况或注意事项
  • 使用对话式语言
  • 将教学内容与参考文档混在一起(这是 Learn 的职责)
  • 记录过去的错误或已修复的问题
  • 收录罕见的边缘情况(例如 this 绑定、少见的类模式)
  • 添加解释“为什么你会需要这个”的语句——Usage 章节中的示例会说明这一点
  • 例外:Pitfall 和 DeepDive 提示框可以使用稍微口语化的措辞

页面模板

类型 A:Hook/函数

适用情况: 文档介绍 React Hook 和独立函数(useState、useEffect、memo、lazy 等)

---
title: hookName
---

<Intro>

`hookName` is a React Hook that lets you [brief description].

```js
const result = hookName(arg)

参考 {/reference/}

hookName(arg) {/hookname/}

在组件顶层调用 hookName,以便……

[signature example with annotations]

在下方查看更多示例。

参数 {/parameters/}
  • arg:参数说明。
返回值 {/returns/}

返回值说明。

注意事项 {/caveats/}
  • 有关用法的重要注意事项。

用法 {/usage/}

常见用例 {/common-use-case/}

使用 Sandpack 示例进行说明……


故障排查 {/troubleshooting/}

常见问题 {/common-problem/}

如何解决……


---

### Type B: Component

**When to use:** Documenting React components (Suspense, Fragment, Activity, StrictMode)

```mdx
---
title: <ComponentName>
---

<Intro>

`<ComponentName>` lets you [primary action].

```js
<ComponentName prop={value}>
  <Children />
</ComponentName>

参考 {/reference/}

<ComponentName> {/componentname/}

[组件的用途和行为]

Props {/props/}
  • propName:Prop 说明……
  • 可选 optionalProp:说明……
注意事项 {/caveats/}
  • [此组件特有的注意事项]

**Key differences from Hook pages:**
- Title uses JSX syntax: `<ComponentName>`
- Uses `#### Props` instead of `#### Parameters`
- Reference heading uses JSX: `` ### `<ComponentName>` ``

---

### Type C: Configuration

**When to use:** Documenting React Compiler configuration options

```mdx
---
title: optionName
---

<Intro>

The `optionName` option [controls/specifies/determines] [what it does].

</Intro>

```js
{
  optionName: 'value' // Quick example
}

参考 {/reference/}

optionName {/optionname/}

[选项用途说明]

类型 {/type/}
'value1' | 'value2' | 'value3'
默认值 {/default-value/}

'value1'

选项 {/options/}
  • 'value1'(默认):说明
  • 'value2':说明
  • 'value3':说明
注意事项 {/caveats/}
  • [用法注意事项]

---

### Type D: Directive

**When to use:** Documenting directives like 'use server', 'use client', 'use memo'

```mdx
---
title: "'use directive'"
titleForTitleTag: "'use directive' directive"
---

<RSC>

`'use directive'` is for use with [React Server Components](/reference/rsc/server-components).

</RSC>

<Intro>

`'use directive'` marks [what it marks] for [purpose].

```js {1}
function MyComponent() {
  'use directive';
  // ...
}

参考 {/reference/}

'use directive' {/use-directive/}

在[位置]开头添加 'use directive',以便[执行操作]。

注意事项 {/caveats/}
  • 'use directive' 必须位于最开头……
  • 指令必须使用单引号或双引号编写,不能使用反引号。
  • [其他位置/语法注意事项]

**Key characteristics:**
- Title includes quotes: `title: "'use server'"`
- Uses `titleForTitleTag` for browser tab title
- `<RSC>` block appears before `<Intro>`
- Caveats focus on placement and syntax requirements

---

### Type E: ESLint Rule

**When to use:** Documenting ESLint plugin rules

```mdx
---
title: rule-name
---

<Intro>
Validates that [what the rule checks].
</Intro>

## Rule Details {/*rule-details*/}

[Explanation of why this rule exists and React's underlying assumptions]

## Common Violations {/*common-violations*/}

[Description of violation patterns]

### Invalid {/*invalid*/}

Examples of incorrect code for this rule:

```js
// X Missing dependency
useEffect(() => {
  console.log(count);
}, []); // Missing 'count'
有效示例 {/valid/}

此规则的正确代码示例:

// checkmark All dependencies included
useEffect(() => {
  console.log(count);
}, [count]);

故障排查 {/troubleshooting/}

[问题描述] {/problem-slug/}

[解决方案]

选项 {/options/}

[适用时填写配置选项]


**Key characteristics:**
- Intro is a single "Validates that..." sentence
- Uses "Invalid"/"Valid" sections with emoji-prefixed code comments
- Rule Details explains "why" not just "what"

---

### Type F: Index/Category

**When to use:** Overview pages listing multiple APIs in a category

```mdx
---
title: "Built-in React [Type]"
---

<Intro>

*Concept* let you [purpose]. Brief scope statement.

</Intro>

---

## Category Name {/*category-name*/}

*Concept* explanation with [Learn section link](/learn/topic).

To [action], use one of these [Type]:

* [`apiName`](/reference/react/apiName) lets you [action].
* [`apiName`](/reference/react/apiName) declares [thing].

```js
function Example() {
  const value = useHookName(args);
}

你自己的 [类型] {/your-own-type/}

你也可以将自己的定义写成 JavaScript 函数。


**Key characteristics:**
- Title format: "Built-in React [Type]"
- Italicized concept definitions
- Horizontal rules between sections
- Closes with "Your own [Type]" section

---

## Advanced Patterns

### Multi-Function Documentation

**When to use:** When a hook returns a function that needs its own documentation (useState's setter, useReducer's dispatch)

```md
### `hookName(args)` {/*hookname*/}

[Main hook documentation]

#### Parameters {/*parameters*/}
#### Returns {/*returns*/}
#### Caveats {/*caveats*/}

---

### `set` functions, like `setSomething(nextState)` {/*setstate*/}

The `set` function returned by `hookName` lets you [action].

#### Parameters {/*setstate-parameters*/}
#### Returns {/*setstate-returns*/}
#### Caveats {/*setstate-caveats*/}

主要约定:

  • 水平分隔线(---)用于分隔主钩子和返回的函数
  • 标题 ID 包含前缀:{/*setstate-parameters*/} 与 {/*parameters*/}
  • 使用通用名称:“set 函数”,而不是 “setCount”

复合返回对象

适用场景: 函数返回包含多个属性或方法的对象时(createContext)

### `createContext(defaultValue)` {/*createcontext*/}

[Main function documentation]

#### Returns {/*returns*/}

`createContext` returns a context object.

**The context object itself does not hold any information.** It represents...

* `SomeContext` lets you provide the context value.
* `SomeContext.Consumer` is an alternative way to read context.

---

### `SomeContext` Provider {/*provider*/}

[Documentation for Provider]

#### Props {/*provider-props*/}

---

### `SomeContext.Consumer` {/*consumer*/}

[Documentation for Consumer]

#### Props {/*consumer-props*/}

写作模式

各类页面的开篇句
页面类型模式示例
Hook`hookName` is a React Hook that lets you [action]."useState is a React Hook that lets you add a state variable to your component."
组件`<ComponentName>` lets you [action]."<Suspense> lets you display a fallback until its children have finished loading."
API`apiName` lets you [action]."memo lets you skip re-rendering a component when its props are unchanged."
配置The `optionName` option [controls/specifies/determines] [what]."The target option specifies which React version the compiler generates code for."
指令`'directive'` [marks/opts/prevents] [what] for [purpose]."'use server' marks a function as callable from the client."
ESLint 规则Validates that [condition]."Validates that dependency arrays for React hooks contain all necessary dependencies."

参数模式

简单参数:

* `paramName`: Description of what it does.

可选参数:

* **optional** `paramName`: Description of what it does.

具有特殊函数行为的参数:

* `initialState`: The value you want the state to be initially. It can be a value of any type, but there is a special behavior for functions. This argument is ignored after the initial render.
  * If you pass a function as `initialState`, it will be treated as an _initializer function_. It should be pure, should take no arguments, and should return a value of any type.

带子参数的回调参数:

* `subscribe`: A function that takes a single `callback` argument and subscribes it to the store. When the store changes, it should invoke the provided `callback`. The `subscribe` function should return a function that cleans up the subscription.

嵌套选项对象:

* **optional** `options`: An object with options for this React root.
  * **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary.
  * **optional** `onUncaughtError`: Callback called when an error is thrown and not caught.
  * **optional** `identifierPrefix`: A string prefix React uses for IDs generated by `useId`.

返回值模式

返回单个值:

`hookName` returns the current value. The value will be the same as `initialValue` during the first render.

返回数组(编号列表):

`useState` returns an array with exactly two values:

1. The current state. During the first render, it will match the `initialState` you have passed.
2. The [`set` function](#setstate) that lets you update the state to a different value and trigger a re-render.

返回对象(项目符号列表):

`createElement` returns a React element object with a few properties:

* `type`: The `type` you have passed.
* `props`: The `props` you have passed except for `ref` and `key`.
* `ref`: The `ref` you have passed. If missing, `null`.
* `key`: The `key` you have passed, coerced to a string. If missing, `null`.

返回 Promise:

`prerender` returns a Promise:
- If rendering is successful, the Promise will resolve to an object containing:
  - `prelude`: a [Web Stream](MDN-link) of HTML.
  - `postponed`: a JSON-serializable object for resumption.
- If rendering fails, the Promise will be rejected.

返回包装后的函数:

`cache` returns a cached version of `fn` with the same type signature. It does not call `fn` in the process.

When calling `cachedFn` with given arguments, it first checks if a cached result exists. If cached, it returns the result. If not, it calls `fn`, stores the result, and returns it.

注意事项模式

标准 Hook 注意事项(几乎总是 Hooks 部分的第一条):

* `useXxx` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.

稳定标识注意事项(针对返回的函数):

* The `set` function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire.

Strict Mode 注意事项:

* In Strict Mode, React will **call your render function twice** in order to help you find accidental impurities. This is development-only behavior and does not affect production.

附带代码示例的注意事项:

* It's not recommended to _suspend_ a render based on a store value returned by `useSyncExternalStore`. For example, the following is discouraged:

  ```js
  const selectedProductId = useSyncExternalStore(...);
  const data = use(fetchItem(selectedProductId)) // X Don't suspend based on store value

**Canary caveat:**
```md
* <CanaryBadge /> If you want to pass `ref` to a Fragment, you can't use the `<>...</>` syntax.

故障排查模式

标题格式(以第一人称表述问题):

### I've updated the state, but logging gives me the old value {/*old-value*/}

### My initializer or updater function runs twice {/*runs-twice*/}

### I want to read the latest state from a callback {/*read-latest-state*/}

错误消息格式:

### I'm getting an error: "Too many re-renders" {/*too-many-rerenders*/}

### I'm getting an error: "Rendered more hooks than during the previous render" {/*more-hooks*/}

Lint 错误格式:

### I'm getting a lint error: "[exact error message]" {/*lint-error-slug*/}

问题解决结构:

  1. 通过展示问题的代码说明问题
  2. 解释问题发生的原因
  3. 提供包含修正后代码的解决方案
  4. 链接到 Learn 部分,深入了解相关内容

代码注释约定

关于代码注释约定(错误/正确、旧版/推荐、服务器/客户端标注、包大小注释),请调用 /docs-sandpack。


链接描述模式
模式示例
“让你可以” + 操作"memo lets you skip re-rendering when props are unchanged."
“声明” + 内容"useState declares a state variable that you can update directly."
“读取” + 内容"useContext reads and subscribes to a context."
“连接” + 内容"useEffect connects a component to an external system."
“与……搭配使用”"Used with useContext."
“类似于”"Similar to useTransition."

组件模式

如需全面了解 MDX 组件模式(Note、Pitfall、DeepDive、Recipes、Deprecated、RSC、Canary、Diagram、Code Steps),请调用 /docs-components。

如需了解 Sandpack 专属模式和代码风格,请调用 /docs-sandpack。

参考页面专属组件规则

参考页面中的组件位置:

  • <RSC> 放在页面顶部的 <Intro> 之前
  • 页面级弃用的 <Deprecated> 放在 <Intro> 之后
  • 方法级弃用的 <Deprecated> 放在方法标题之后
  • <Canary> 包装器以内联形式放在 <Intro> 中
  • <CanaryBadge /> 出现在标题、属性列表和注意事项中

故障排查专属组件:

  • 使用第一人称的问题标题
  • 相关时交叉引用陷阱 ID

提示框间距:

  • 不要连续放置多个 Pitfall 或多个 Note
  • 将相关警告合并到一个带标题的分节中,或用正文/代码分隔
  • 多部分深入探讨可以连续放置多个 DeepDive
  • 请参阅 /docs-components 中的提示框间距规则

内容原则

简介部分
  • 一句话,最多约 15 个词——说明 Hook 的作用,而非工作原理
  • ✅ "useEffectEvent is a React Hook that lets you separate events from Effects."
  • ❌ "useEffectEvent is a React Hook that lets you extract non-reactive logic from your Effects into a reusable function called an Effect Event."
参考代码示例
  • 只展示 API 调用(5-10 行),不要展示完整组件
  • 将完整组件示例移至用法部分
用法部分结构
  1. 第一个示例:核心心智模型——用最简单的具体示例展示典型用例
  2. 后续示例:典型用例——说明 原因(例如“避免重新连接到外部系统”),并展示具体的 做法
    • 优先选择广泛适用的典型用例,而不是多个狭窄的具体示例
    • 分节标题本身就是讲解内容——“我应该在什么时候使用它?”应由标题回答
包含与排除的内容
  • 绝不记录过去的 Bug 或已修复的问题
  • 包含大多数开发者会遇到的边缘情况
  • 排除冷门边缘情况(例如 this 绑定、罕见的类模式)
注意事项部分
  • 包含 linter 强制执行的规则或会立即导致错误的规则
  • 包含基本的使用限制
  • 除非实现细节会影响使用,否则不要包含
  • 不要重复其他地方已说明的内容
  • 尽可能将每条注意事项限制为一句话
故障排查部分
  • 错误标题仅采用以下格式:“我遇到了错误:‘[message]’”
  • 绝不记录过去的 Bug——如果问题已修复,就不应放在这里
  • 聚焦于开发者今天实际会遇到的错误
DeepDive 内容
  • 恰到好处原则——对好奇的开发者来说足够深入,同时又不会让人不堪重负
  • 回答“为什么要这样设计?”,而不是罗列详尽的技术细节
  • 跳过此部分的读者不应因此错过使用 API 的必要信息
  • 如果解释变得冗长,你很可能讲得太多了

特定领域指南

Hooks

返回函数的文档说明:

  • 将 setter/dispatch 函数分别作为 ### 分节进行说明
  • 使用通用名称:“set 函数”,而不是“setCount”
  • 说明返回函数具有稳定标识这一注意事项

依赖数组文档说明:

  • 列出哪些内容属于响应式值
  • 说明何时会忽略依赖项
  • 链接到移除 Effect 依赖项指南

Recipes 用法:

  • 用有意义的 titleText 对相关示例分组
  • 每个 recipe 都包含简短介绍、Sandpack 和 <Solution />

组件

Props 文档说明:

  • 使用 #### Props,而不是 #### Parameters
  • 可选 props 前加上 **optional**
  • 对仅限 canary 的 props 使用内联 <CanaryBadge />

标题/分节标题中的 JSX 语法:

  • Frontmatter 标题:title: <Suspense>
  • 参考页面标题:### `<Suspense>` {/*suspense*/}
React-DOM

常见 props 的链接:

`<input>` supports all [common element props.](/reference/react-dom/components/common#common-props)

Props 分类:

  • 将受控和非受控 props 分开归类
  • 使用 action 模式记录表单专用 props
  • 为标准 HTML 属性提供 MDN 链接

特定环境说明:

<Note>

This API is specific to Node.js. Environments with [Web Streams](MDN-link), like Deno and modern edge runtimes, should use [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream) instead.

</Note>

渐进增强:

  • 说明对没有 JavaScript 的用户有哪些好处
  • 解释 Server Function 与表单 action 的集成
  • 展示隐藏表单字段和 .bind() 模式

RSC

RSC 横幅(位于 Intro 之前): 对于仅限 Server Component 使用的 API,始终将 <RSC> 组件放在 <Intro> 之前。

序列化类型列表: 记录 Server Function 参数时,列出支持的类型:

Supported types for Server Function arguments:

* Primitives
	* [string](MDN-link)
	* [number](MDN-link)
* Iterables containing serializable values
	* [Array](MDN-link)
	* [Map](MDN-link)

Notably, these are not supported:
* React elements, or [JSX](/learn/writing-markup-with-jsx)
* Functions (other than Server Functions)

包体积比较:

  • 对仅限服务端的导入显示“未包含在包中”
  • 使用 gzip 标注客户端包体积:// 35.9K (11.2K gzipped)

Compiler

配置页面结构:

  • 类型(联合类型或接口)
  • 默认值
  • 选项/有效值及其说明

指令文档:

  • 放置要求至关重要
  • 使用模式交互表展示各种组合
  • 对逃生舱模式采用“谨慎使用”+“规划移除”模式

库作者指南:

  • 开篇优先面向目标受众
  • 好处/原因部分
  • 编号步骤式设置指南

ESLint

规则详情部分:

  • 解释“为什么”,而不只是“是什么”
  • 聚焦 React 的底层假设
  • 说明违反规则会造成什么后果

无效/有效部分:

  • 使用标准开场白:“此规则的[不]正确代码示例:”
  • 无效示例使用 X 表情符号,有效示例使用勾号
  • 使用行内注释说明违规之处

配置选项:

  • 展示共享设置(首选)
  • 展示规则级选项(向后兼容)
  • 说明两者同时存在时的优先级

边缘情况

对于已弃用、Canary 和特定版本的组件模式(放置位置、语法、示例),请调用 /docs-components。

快速放置规则:

  • 页面级 <Deprecated> 放在 <Intro> 之后;方法级放在标题之后
  • <Canary> 在 Intro 中行内包裹;标题/props/注意事项中使用 <CanaryBadge />
  • 版本说明使用 <Note>,并采用“从 React 19 开始……”模式

已移除的索引页 API

## Removed APIs {/*removed-apis*/}

These APIs were removed in React 19:

* [`render`](https://18.react.dev/reference/react-dom/render): use [`createRoot`](/reference/react-dom/client/createRoot) instead.

对于已移除 API 的文档,请链接到旧版本文档(18.react.dev)。


关键规则

  1. 必须添加标题 ID: ## Title {/*title-id*/}(小写,使用连字符)
  2. Sandpack 主文件需要 export default
  3. 活动文件语法: ```js src/File.js active
  4. 故障排除中的错误标题: 使用 ### I'm getting an error: "[message]" {/*id*/}
  5. 标题之间必须使用分隔线(---)(见下文“分隔线”部分)
  6. 必须使用 InlineToc: 始终在 Intro 后添加 <InlineToc />
  7. 参数格式保持一致: 使用 * \paramName`: description;可选参数前加 optional`
  8. 数组返回值使用编号列表: Hook 返回数组时,在 Returns 部分使用编号列表
  9. 返回函数使用通用名称: 使用“set 函数”,而不是“setCount”
  10. Props 与 Parameters: 组件(类型 B)使用 #### Props;Hook/API(类型 A)使用 #### Parameters
  11. RSC 放置位置: <RSC> 组件放在 <Intro> 之前,而不是之后
  12. Canary 标记: 在 Intro 中行内使用 <Canary> 包裹;标题/props 中使用 <CanaryBadge />
  13. Deprecated 放置位置: 页面级 <Deprecated> 放在 <Intro> 之后;方法级放在标题之后
  14. 代码注释表情符号: 代码示例中,错误用 X,正确用勾号
  15. Pitfall/Note 不要连续出现: 合并为一个带标题子节的组件,或用正文/代码隔开(见 /docs-components)

关于组件标题层级约定(DeepDive、Pitfall、Note、Recipe 标题),请参阅 /docs-components。

章节分隔线

使用 --- 水平线,在视觉上分隔主要章节:

  • 在 <InlineToc /> 后 - 在 ## Reference 标题前
  • 在 API 子章节之间 - 分隔不同的函数/钩子定义(例如,在 useState() 和 set functions 之间)
  • 在 ## Usage 前 - 将 API 参考与示例分隔开
  • 在 ## Troubleshooting 前 - 将正文与故障排查内容分隔开
  • 在每个 Usage 子章节之间 - 切换到新的主要用例时

--- 前后都要留一个空行。

章节 ID 约定
章节ID 格式
主函数{/*functionname*/}
返回的函数{/*setstate*/}、{/*dispatch*/}
返回函数的子章节{/*setstate-parameters*/}
故障排查条目{/*problem-description-slug*/}
易错点{/*pitfall-description*/}
深入探讨{/*deep-dive-topic*/}

评论

支持 Markdown