docs-writer-reference
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReference Page Writer
参考页面撰写指南
Quick Reference
快速参考
Page Type Decision Tree
页面类型决策树
- Is it a Hook? Use Type A (Hook/Function)
- Is it a React component ()? Use Type B (Component)
<Something> - Is it a compiler configuration option? Use Type C (Configuration)
- Is it a directive ()? Use Type D (Directive)
'use something' - Is it an ESLint rule? Use Type E (ESLint Rule)
- Is it listing multiple APIs? Use Type F (Index/Category)
- 是Hook吗?使用类型A(Hook/函数)
- 是React组件()吗?使用类型B(组件)
<Something> - 是编译器配置选项吗?使用类型C(配置)
- 是指令()吗?使用类型D(指令)
'use something' - 是ESLint规则吗?使用类型E(ESLint规则)
- 是列出多个API的页面吗?使用类型F(索引/分类)
Component Selection
组件选择
For component selection and patterns, invoke .
/docs-components如需了解组件选择和相关模式,请查看。
/docs-componentsVoice & Style
语气与风格
Voice: Authoritative technical reference writer
Tone: Precise, comprehensive, neutral
For tone, capitalization, jargon, and prose patterns, invoke .
/docs-voiceDo:
- Start with single-line description: "is a React Hook that lets you..."
useState - Include Parameters, Returns, Caveats sections for every API
- Document edge cases most developers will encounter
- Use section dividers between major sections
- Include "See more examples below" links
- Be assertive, not hedging - "This is designed for..." not "This helps avoid issues with..."
- State facts, not benefits - "The callback always accesses the latest values" not "This helps avoid stale closures"
- Use minimal but meaningful names - or
onEventoveronTickonSomething
Don't:
- Skip the InlineToc component
- Omit error cases or caveats
- Use conversational language
- Mix teaching with reference (that's Learn's job)
- Document past bugs or fixed issues
- Include niche edge cases (e.g., binding, rare class patterns)
this - Add phrases explaining "why you'd want this" - the Usage section examples do that
- Exception: Pitfall and DeepDive asides can use slightly conversational phrasing
语气: 权威的技术参考文档撰写者
语调: 精准、全面、中立
如需了解语调、大小写、术语和行文模式,请查看。
/docs-voice建议:
- 以单行描述开头:"是一个React Hook,可让你..."
useState - 为每个API包含参数、返回值、注意事项章节
- 记录大多数开发者会遇到的边缘情况
- 在主要章节之间使用分隔线
- 包含“查看下方更多示例”的链接
- 表述直接,避免含糊 - 用“这是为...设计的”而非“这有助于避免...的问题”
- 陈述事实而非优势 - 用“回调始终访问最新值”而非“这有助于避免闭包过时问题”
- 使用简洁且有意义的命名 - 用或
onEvent而非onTickonSomething
禁忌:
- 跳过InlineToc组件
- 省略错误案例或注意事项
- 使用口语化语言
- 将教学内容与参考内容混合(那是Learn板块的职责)
- 记录已修复的历史Bug
- 包含小众边缘情况(如绑定、罕见的类模式)
this - 添加解释“你为什么需要这个”的表述 - 使用场景章节的示例会说明这一点
- 例外:Pitfall和DeepDive附注可使用略带口语化的表述
Page Templates
页面模板
Type A: Hook/Function
类型A:Hook/函数
When to use: Documenting React hooks and standalone functions (useState, useEffect, memo, lazy, etc.)
mdx
---
title: hookName
---
<Intro>
`hookName` is a React Hook that lets you [brief description].
```js
const result = hookName(arg)适用场景: 记录React Hook和独立函数(useState、useEffect、memo、lazy等)
mdx
---
title: hookName
---
<Intro>
`hookName` 是一个React Hook,可让你[简要描述]。
```js
const result = hookName(arg)Reference {/reference/}
参考 {/reference/}
hookName(arg)
{/hookname/}
hookName(arg)hookName(arg)
{/hookname/}
hookName(arg)Call at the top level of your component to...
hookNamejs
[signature example with annotations]Parameters {/parameters/}
参数 {/parameters/}
- : Description of the parameter.
arg
- : 参数说明。
arg
Returns {/returns/}
返回值 {/returns/}
Description of return value.
返回值说明。
Caveats {/caveats/}
注意事项 {/caveats/}
- Important caveat about usage.
- 重要的使用注意事项。
Usage {/usage/}
使用场景 {/usage/}
Common Use Case {/common-use-case/}
常见用例 {/common-use-case/}
Explanation with Sandpack examples...
带Sandpack示例的说明...
Troubleshooting {/troubleshooting/}
问题排查 {/troubleshooting/}
Common Problem {/common-problem/}
常见问题 {/common-problem/}
How to solve it...
---解决方法...
---Type B: Component
类型B:组件
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>适用场景: 记录React组件(Suspense、Fragment、Activity、StrictMode)
mdx
---
title: <ComponentName>
---
<Intro>
`<ComponentName>` 可让你[主要功能]。
```js
<ComponentName prop={value}>
<Children />
</ComponentName>Reference {/reference/}
参考 {/reference/}
<ComponentName>
{/componentname/}
<ComponentName><ComponentName>
{/componentname/}
<ComponentName>[Component purpose and behavior]
[组件用途和行为说明]
Props {/props/}
属性 {/props/}
- : Description of the prop...
propName - optional : Description...
optionalProp
- : 属性说明...
propName - 可选 : 说明...
optionalProp
Caveats {/caveats/}
注意事项 {/caveats/}
- [Caveats specific to this component]
**Key differences from Hook pages:**
- Title uses JSX syntax: `<ComponentName>`
- Uses `#### Props` instead of `#### Parameters`
- Reference heading uses JSX: `` ### `<ComponentName>` ``
---- [该组件特有的注意事项]
**与Hook页面的主要区别:**
- 标题使用JSX语法:`<ComponentName>`
- 使用`#### 属性`而非`#### 参数`
- 参考标题使用JSX:`` ### `<ComponentName>` ``
---Type C: Configuration
类型C:配置
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
}适用场景: 记录React Compiler配置选项
mdx
---
title: optionName
---
<Intro>
`optionName`选项[控制/指定/决定][功能描述]。
</Intro>
```js
{
optionName: 'value' // 快速示例
}Reference {/reference/}
参考 {/reference/}
optionName
{/optionname/}
optionNameoptionName
{/optionname/}
optionName[Description of the option's purpose]
[选项用途说明]
Type {/type/}
类型 {/type/}
'value1' | 'value2' | 'value3''value1' | 'value2' | 'value3'Default value {/default-value/}
默认值 {/default-value/}
'value1''value1'Options {/options/}
可选值 {/options/}
- (default): Description
'value1' - : Description
'value2' - : Description
'value3'
- (默认):说明
'value1' - :说明
'value2' - :说明
'value3'
Caveats {/caveats/}
注意事项 {/caveats/}
- [Usage caveats]
---- [使用注意事项]
---Type D: Directive
类型D:指令
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';
// ...
}适用场景: 记录、、等指令
'use server''use client''use memo'mdx
---
title: "'use directive'"
titleForTitleTag: "'use directive' directive"
---
<RSC>
`'use directive'` 用于[React Server Components](/reference/rsc/server-components)。
</RSC>
<Intro>
`'use directive'` 标记[标记对象]以[用途]。
```js {1}
function MyComponent() {
'use directive';
// ...
}Reference {/reference/}
参考 {/reference/}
'use directive'
{/use-directive/}
'use directive''use directive'
{/use-directive/}
'use directive'Add at the beginning of [location] to [action].
'use directive'在[位置]的开头添加以[作用]。
'use directive'Caveats {/caveats/}
注意事项 {/caveats/}
- must be at the very beginning...
'use directive' - The directive must be written with single or double quotes, not backticks.
- [Other placement/syntax caveats]
**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
---- 必须放在最开头...
'use directive' - 指令必须使用单引号或双引号,不能使用反引号。
- [其他位置/语法注意事项]
**主要特征:**
- 标题包含引号:`title: "'use server'"`
- 使用`titleForTitleTag`设置浏览器标签页标题
- `<RSC>`块出现在`<Intro>`之前
- 注意事项重点关注位置和语法要求
---Type E: ESLint Rule
类型E:ESLint规则
When to use: Documenting ESLint plugin rules
mdx
---
title: rule-name
---
<Intro>
Validates that [what the rule checks].
</Intro>适用场景: 记录ESLint插件规则
mdx
---
title: rule-name
---
<Intro>
验证[规则检查内容]。
</Intro>Rule Details {/rule-details/}
规则详情 {/rule-details/}
[Explanation of why this rule exists and React's underlying assumptions]
[说明该规则存在的原因以及React的底层假设]
Common Violations {/common-violations/}
常见违规情况 {/common-violations/}
[Description of violation patterns]
[违规模式说明]
Invalid {/invalid/}
无效代码 {/invalid/}
Examples of incorrect code for this rule:
js
// X Missing dependency
useEffect(() => {
console.log(count);
}, []); // Missing 'count'该规则的错误代码示例:
js
// ❌ 缺少依赖项
useEffect(() => {
console.log(count);
}, []); // 缺少'count'Valid {/valid/}
有效代码 {/valid/}
Examples of correct code for this rule:
js
// checkmark All dependencies included
useEffect(() => {
console.log(count);
}, [count]);该规则的正确代码示例:
js
// ✅ 包含所有依赖项
useEffect(() => {
console.log(count);
}, [count]);Troubleshooting {/troubleshooting/}
问题排查 {/troubleshooting/}
[Problem description] {/problem-slug/}
[问题描述] {/problem-slug/}
[Solution]
[解决方案]
Options {/options/}
配置选项 {/options/}
[Configuration options if applicable]
**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
类型F:索引/分类
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>
---适用场景: 列出某一分类下多个API的概览页面
mdx
---
title: "内置React [类型]"
---
<Intro>
*概念*可让你[用途]。简要范围说明。
</Intro>
---Category Name {/category-name/}
分类名称 {/category-name/}
Concept explanation with Learn section link.
To [action], use one of these [Type]:
js
function Example() {
const value = useHookName(args);
}Your own [Type] {/your-own-type/}
自定义[类型] {/your-own-type/}
You can also define your own as JavaScript functions.
**Key characteristics:**
- Title format: "Built-in React [Type]"
- Italicized concept definitions
- Horizontal rules between sections
- Closes with "Your own [Type]" section
---你也可以自定义为JavaScript函数。
**主要特征:**
- 标题格式:“内置React [类型]”
- 概念定义使用斜体
- 章节之间使用水平分隔线
- 以“自定义[类型]”章节结尾
---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
undefined适用场景: 当Hook返回的函数需要单独文档时(如useState的setter、useReducer的dispatch)
md
undefinedhookName(args)
{/hookname/}
hookName(args)hookName(args)
{/hookname/}
hookName(args)[Main hook documentation]
[主Hook文档]
Parameters {/parameters/}
参数 {/parameters/}
Returns {/returns/}
返回值 {/returns/}
Caveats {/caveats/}
注意事项 {/caveats/}
set
functions, like setSomething(nextState)
{/setstate/}
setsetSomething(nextState)set
函数,如setSomething(nextState)
{/setstate/}
setsetSomething(nextState)The function returned by lets you [action].
sethookNamehookNamesetParameters {/setstate-parameters/}
参数 {/setstate-parameters/}
Returns {/setstate-returns/}
返回值 {/setstate-returns/}
Caveats {/setstate-caveats/}
注意事项 {/setstate-caveats/}
**Key conventions:**
- Horizontal rule (`---`) separates main hook from returned function
- Heading IDs include prefix: `{/*setstate-parameters*/}` vs `{/*parameters*/}`
- Use generic names: "set functions" not "setCount"
---
**主要约定:**
- 使用水平分隔线(`---`)分隔主Hook和返回的函数
- 标题ID包含前缀:`{/*setstate-parameters*/}` 对比 `{/*parameters*/}`
- 使用通用名称:“set函数”而非“setCount”
---Compound Return Objects
复合返回对象
When to use: When a function returns an object with multiple properties/methods (createContext)
md
undefined适用场景: 当函数返回包含多个属性/方法的对象时(如createContext)
md
undefinedcreateContext(defaultValue)
{/createcontext/}
createContext(defaultValue)createContext(defaultValue)
{/createcontext/}
createContext(defaultValue)[Main function documentation]
[主函数文档]
Returns {/returns/}
返回值 {/returns/}
createContextThe context object itself does not hold any information. It represents...
- lets you provide the context value.
SomeContext - is an alternative way to read context.
SomeContext.Consumer
createContext上下文对象本身不存储任何信息。 它代表...
- 可让你提供上下文值。
SomeContext - 是读取上下文的替代方式。
SomeContext.Consumer
SomeContext
Provider {/provider/}
SomeContextSomeContext
Provider {/provider/}
SomeContext[Documentation for Provider]
[Provider文档]
Props {/provider-props/}
属性 {/provider-props/}
SomeContext.Consumer
{/consumer/}
SomeContext.ConsumerSomeContext.Consumer
{/consumer/}
SomeContext.Consumer[Documentation for Consumer]
[Consumer文档]
Props {/consumer-props/}
属性 {/consumer-props/}
---
---Writing Patterns
写作模式
Opening Lines by Page Type
按页面类型划分的开篇句式
| Page Type | Pattern | Example |
|---|---|---|
| Hook | | " |
| Component | | " |
| API | | " |
| Configuration | | "The |
| Directive | | " |
| ESLint Rule | | "Validates that dependency arrays for React hooks contain all necessary dependencies." |
| 页面类型 | 句式 | 示例 |
|---|---|---|
| Hook | | " |
| 组件 | | " |
| API | | " |
| 配置 | | " |
| 指令 | | " |
| ESLint规则 | | "验证React Hook的依赖数组是否包含所有必要的依赖项。" |
Parameter Patterns
参数模式
Simple parameter:
md
* `paramName`: Description of what it does.Optional parameter:
md
* **optional** `paramName`: Description of what it does.Parameter with special function behavior:
md
* `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.Callback parameter with sub-parameters:
md
* `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.Nested options object:
md
* **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`.简单参数:
md
* `paramName`: 参数功能说明。可选参数:
md
* **可选** `paramName`: 参数功能说明。具有特殊函数行为的参数:
md
* `initialState`: 你希望状态初始化为的值。可以是任意类型,但传入函数时有特殊行为。该参数在初始渲染后会被忽略。
* 如果传入函数作为`initialState`,它将被视为_初始化函数_。它应该是纯函数,不接受参数,返回任意类型的值。带子参数的回调参数:
md
* `subscribe`: 接收单个`callback`参数并将其订阅到存储的函数。当存储内容变化时,应调用提供的`callback`。`subscribe`函数应返回一个用于清理订阅的函数。嵌套选项对象:
md
* **可选** `options`: 包含React根选项的对象。
* **可选** `onCaughtError`: 当React在Error Boundary中捕获错误时调用的回调。
* **可选** `onUncaughtError`: 当错误被抛出且未被捕获时调用的回调。
* **可选** `identifierPrefix`: React用于`useId`生成ID的字符串前缀。Return Value Patterns
返回值模式
Single value return:
md
`hookName` returns the current value. The value will be the same as `initialValue` during the first render.Array return (numbered list):
md
`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.Object return (bulleted list):
md
`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 return:
md
`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.Wrapped function return:
md
`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.单值返回:
md
`hookName`返回当前值。在首次渲染时,该值与`initialValue`相同。数组返回(编号列表):
md
`useState`返回一个恰好包含两个值的数组:
1. 当前状态。在首次渲染时,它与你传入的`initialState`一致。
2. 用于更新状态为不同值并触发重新渲染的[`set`函数](#setstate)。对象返回(项目符号列表):
md
`createElement`返回一个包含以下几个属性的React元素对象:
* `type`: 你传入的`type`。
* `props`: 你传入的`props`(`ref`和`key`除外)。
* `ref`: 你传入的`ref`。如果未传入,则为`null`。
* `key`: 你传入的`key`,被转换为字符串。如果未传入,则为`null`。Promise返回:
md
`prerender`返回一个Promise:
- 如果渲染成功,Promise将解析为包含以下内容的对象:
- `prelude`: HTML的[Web Stream](MDN-link)。
- `postponed`: 可序列化的JSON对象,用于恢复渲染。
- 如果渲染失败,Promise将被拒绝。包装函数返回:
md
`cache`返回`fn`的缓存版本,具有相同的类型签名。在此过程中不会调用`fn`。
当使用给定参数调用`cachedFn`时,它首先检查是否存在缓存结果。如果有缓存,则返回结果;如果没有,则调用`fn`,存储结果并返回。Caveats Patterns
注意事项模式
Standard Hook caveat (almost always first for Hooks):
md
* `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.Stable identity caveat (for returned functions):
md
* 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 caveat:
md
* 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.Caveat with code example:
md
* 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.标准Hook注意事项(Hook的第一条注意事项几乎总是这个):
md
* `useXxx`是一个Hook,因此你只能在**组件或自定义Hook的顶层**调用它。不能在循环或条件语句中调用。如果需要,请提取新组件并将状态移入其中。稳定标识注意事项(针对返回的函数):
md
* `set`函数具有稳定的标识,因此你经常会看到它被排除在Effect的依赖项之外,但将其包含在内也不会导致Effect触发。严格模式注意事项:
md
* 在严格模式下,React会**调用你的渲染函数两次**,以帮助你发现意外的不纯操作。这仅在开发环境中存在,不影响生产环境。带代码示例的注意事项:
md
* 不建议基于`useSyncExternalStore`返回的存储值来暂停渲染。例如,不建议以下写法:
```js
const selectedProductId = useSyncExternalStore(...);
const data = use(fetchItem(selectedProductId)) // ❌ 不要基于存储值暂停渲染
**Canary版本注意事项:**
```md
* <CanaryBadge /> 如果你想将`ref`传递给Fragment,不能使用`<>...</>`语法。Troubleshooting Patterns
问题排查模式
Heading format (first person problem statements):
md
undefined标题格式(第一人称问题陈述):
md
undefinedI've updated the state, but logging gives me the old value {/old-value/}
我更新了状态,但日志显示旧值 {/old-value/}
My initializer or updater function runs twice {/runs-twice/}
我的初始化函数或更新函数运行了两次 {/runs-twice/}
I want to read the latest state from a callback {/read-latest-state/}
我想从回调中读取最新状态 {/read-latest-state/}
**Error message format:**
```md
**错误消息格式:**
```mdI'm getting an error: "Too many re-renders" {/too-many-rerenders/}
我遇到了错误:“Too many re-renders” {/too-many-rerenders/}
I'm getting an error: "Rendered more hooks than during the previous render" {/more-hooks/}
我遇到了错误:“Rendered more hooks than during the previous render” {/more-hooks/}
**Lint error format:**
```md
**Lint错误格式:**
```mdI'm getting a lint error: "[exact error message]" {/lint-error-slug/}
我遇到了Lint错误:“[确切错误消息]” {/lint-error-slug/}
**Problem-solution structure:**
1. State the problem with code showing the issue
2. Explain why it happens
3. Provide the solution with corrected code
4. Link to Learn section for deeper understanding
---
**问题-解决方案结构:**
1. 陈述问题并展示有问题的代码
2. 解释原因
3. 提供修复后的代码解决方案
4. 链接到Learn板块以深入了解
---Code Comment Conventions
代码注释约定
For code comment conventions (wrong/right, legacy/recommended, server/client labeling, bundle size annotations), invoke .
/docs-sandpack如需了解代码注释约定(错误/正确、旧版/推荐、服务端/客户端标记、包大小注释),请查看。
/docs-sandpackLink Description Patterns
链接描述模式
| Pattern | Example |
|---|---|
| "lets you" + action | " |
| "declares" + thing | " |
| "reads" + thing | " |
| "connects" + thing | " |
| "Used with" | "Used with |
| "Similar to" | "Similar to |
| 模式 | 示例 |
|---|---|
| "lets you" + 操作 | " |
| "declares" + 对象 | " |
| "reads" + 对象 | " |
| "connects" + 对象 | " |
| "Used with" | "Used with |
| "Similar to" | "Similar to |
Component Patterns
组件模式
For comprehensive MDX component patterns (Note, Pitfall, DeepDive, Recipes, Deprecated, RSC, Canary, Diagram, Code Steps), invoke .
/docs-componentsFor Sandpack-specific patterns and code style, invoke .
/docs-sandpack如需了解完整的MDX组件模式(Note、Pitfall、DeepDive、Recipes、Deprecated、RSC、Canary、Diagram、Code Steps),请查看。
/docs-components如需了解Sandpack特有的模式和代码风格,请查看。
/docs-sandpackReference-Specific Component Rules
参考页面专属组件规则
Component placement in Reference pages:
- goes before
<RSC>at top of page<Intro> - goes after
<Deprecated>for page-level deprecation<Intro> - goes after method heading for method-level deprecation
<Deprecated> - wrapper goes inline within
<Canary><Intro> - appears in headings, props lists, and caveats
<CanaryBadge />
Troubleshooting-specific components:
- Use first-person problem headings
- Cross-reference Pitfall IDs when relevant
Callout spacing:
- Never place consecutive Pitfalls or consecutive Notes
- Combine related warnings into one with titled subsections, or separate with prose/code
- Consecutive DeepDives OK for multi-part explorations
- See Callout Spacing Rules
/docs-components
参考页面中的组件位置:
- 放在页面顶部的
<RSC>之前<Intro> - 在页面级弃用时放在
<Deprecated>之后<Intro> - 在方法级弃用时放在方法标题之后
<Deprecated> - 包装器内联在
<Canary>中<Intro> - 出现在标题、属性列表和注意事项中
<CanaryBadge />
问题排查专属组件:
- 使用第一人称问题标题
- 相关时交叉引用Pitfall ID
提示框间距:
- 不要连续放置Pitfall或Note
- 将相关警告合并到一个带小标题的组件中,或用正文/代码分隔
- 连续放置DeepDive是允许的,用于多部分探索
- 请查看中的提示框间距规则
/docs-components
Content Principles
内容原则
Intro Section
简介章节
- One sentence, ~15 words max - State what the Hook does, not how it works
- ✅ "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."
useEffectEvent
- 一句话,约15个词以内 - 说明Hook的功能,而非工作原理
- ✅ "是一个React Hook,可让你将事件与Effect分离。"
useEffectEvent - ❌ "是一个React Hook,可让你将非响应式逻辑从Effect中提取到名为Effect Event的可重用函数中。"
useEffectEvent
Reference Code Example
参考代码示例
- Show just the API call (5-10 lines), not a full component
- Move full component examples to Usage section
- 仅展示API调用(5-10行),而非完整组件
- 将完整组件示例移至使用场景章节
Usage Section Structure
使用场景章节结构
- First example: Core mental model - Show the canonical use case with simplest concrete example
- Subsequent examples: Canonical use cases - Name the why (e.g., "Avoid reconnecting to external systems"), show a concrete how
- Prefer broad canonical use cases over multiple narrow concrete examples
- The section title IS the teaching - "When would I use this?" should be answered by the heading
- 第一个示例:核心思维模型 - 展示最典型的用例和最简单的具体示例
- 后续示例:典型用例 - 说明“为什么”(如“避免重新连接到外部系统”),展示具体的“怎么做”
- 优先选择广泛的典型用例,而非多个狭窄的具体示例
- 章节标题就是教学内容 - “我什么时候会用到这个?”应该能从标题中找到答案
What to Include vs. Exclude
内容取舍
- Never document past bugs or fixed issues
- Include edge cases most developers will encounter
- Exclude niche edge cases (e.g., binding, rare class patterns)
this
- 绝不记录已修复的历史Bug
- 包含大多数开发者会遇到的边缘情况
- 排除小众边缘情况(如绑定、罕见的类模式)
this
Caveats Section
注意事项章节
- Include rules the linter enforces or that cause immediate errors
- Include fundamental usage restrictions
- Exclude implementation details unless they affect usage
- Exclude repetition of things explained elsewhere
- Keep each caveat to one sentence when possible
- 包含linter强制执行的规则或会导致直接错误的规则
- 包含基本的使用限制
- 排除实现细节,除非它们影响使用
- 排除其他地方已解释过的重复内容
- 尽可能将每条注意事项控制在一句话以内
Troubleshooting Section
问题排查章节
- Error headings only: "I'm getting an error: '[message]'" format
- Never document past bugs - if it's fixed, it doesn't belong here
- Focus on errors developers will actually encounter today
- 仅使用错误标题:“我遇到了错误:'[消息]'”格式
- 绝不记录已修复的历史Bug - 如果已修复,就不属于这里
- 聚焦于开发者当前实际会遇到的错误
DeepDive Content
DeepDive内容
- Goldilocks principle - Deep enough for curious developers, short enough to not overwhelm
- Answer "why is it designed this way?" - not exhaustive technical details
- Readers who skip it should miss nothing essential for using the API
- If the explanation is getting long, you're probably explaining too much
- 适中原则 - 足够深入以满足好奇的开发者,但又不会过于冗长
- 回答“为什么要这样设计?”而非详尽的技术细节
- 跳过此部分的读者不应错过使用API的任何必要信息
- 如果解释变得过长,你可能解释得太多了
Domain-Specific Guidance
领域特定指南
Hooks
Hooks
Returned function documentation:
- Document setter/dispatch functions as separate sections
### - Use generic names: "set functions" not "setCount"
- Include stable identity caveat for returned functions
Dependency array documentation:
- List what counts as reactive values
- Explain when dependencies are ignored
- Link to removing effect dependencies guide
Recipes usage:
- Group related examples with meaningful titleText
- Each recipe has brief intro, Sandpack, and
<Solution />
返回函数的文档:
- 将setter/dispatch函数作为单独的章节记录
### - 使用通用名称:“set函数”而非“setCount”
- 为返回的函数包含稳定标识注意事项
依赖数组文档:
- 列出哪些属于响应式值
- 解释何时会忽略依赖项
- 链接到移除Effect依赖项的指南
Recipes使用:
- 用有意义的titleText分组相关示例
- 每个Recipe包含简短介绍、Sandpack和
<Solution />
Components
组件
Props documentation:
- Use instead of
#### Props#### Parameters - Mark optional props with prefix
**optional** - Use inline for canary-only props
<CanaryBadge />
JSX syntax in titles/headings:
- Frontmatter title:
title: <Suspense> - Reference heading:
### `<Suspense>` {/*suspense*/}
属性文档:
- 使用而非
#### 属性#### 参数 - 用前缀标记可选属性
**可选** - 对仅在Canary版本中可用的属性使用内联
<CanaryBadge />
标题/标题中的JSX语法:
- 前置元数据标题:
title: <Suspense> - 参考标题:
### `<Suspense>` {/*suspense*/}
React-DOM
React-DOM
Common props linking:
md
`<input>` supports all [common element props.](/reference/react-dom/components/common#common-props)Props categorization:
- Controlled vs uncontrolled props grouped separately
- Form-specific props documented with action patterns
- MDN links for standard HTML attributes
Environment-specific notes:
mdx
<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>Progressive enhancement:
- Document benefits for users without JavaScript
- Explain Server Function + form action integration
- Show hidden form field and patterns
.bind()
通用属性链接:
md
`<input>` 支持所有[通用元素属性。](/reference/react-dom/components/common#common-props)属性分类:
- 受控属性和非受控属性分开分组
- 表单特定属性结合操作模式记录
- 为标准HTML属性添加MDN链接
环境特定说明:
mdx
<Note>
此API特定于Node.js。支持[Web Streams](MDN-link)的环境(如Deno和现代边缘运行时)应使用[`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream)替代。
</Note>渐进式增强:
- 记录无JavaScript时对用户的好处
- 解释Server Function + 表单操作的集成
- 展示隐藏表单字段和模式
.bind()
RSC
RSC
RSC banner (before Intro):
Always place component before for Server Component-only APIs.
<RSC><Intro>Serialization type lists:
When documenting Server Function arguments, list supported types:
md
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)Bundle size comparisons:
- Show "Not included in bundle" for server-only imports
- Annotate client bundle sizes with gzip:
// 35.9K (11.2K gzipped)
RSC横幅(在Intro之前):
对于仅适用于Server Component的API,始终将组件放在之前。
<RSC><Intro>序列化类型列表:
记录Server Function参数时,列出支持的类型:
md
Server Function参数支持的类型:
* 基本类型
* [string](MDN-link)
* [number](MDN-link)
* 包含可序列化值的可迭代对象
* [Array](MDN-link)
* [Map](MDN-link)
不支持的类型:
* React元素或[JSX](/learn/writing-markup-with-jsx)
* 函数(Server Function除外)包大小比较:
- 对仅在服务端导入的内容标注“不包含在客户端包中”
- 标注客户端包的gzip压缩大小:
// 35.9K (11.2K gzipped)
Compiler
编译器
Configuration page structure:
- Type (union type or interface)
- Default value
- Options/Valid values with descriptions
Directive documentation:
- Placement requirements are critical
- Mode interaction tables showing combinations
- "Use sparingly" + "Plan for removal" patterns for escape hatches
Library author guides:
- Audience-first intro
- Benefits/Why section
- Numbered step-by-step setup
配置页面结构:
- 类型(联合类型或接口)
- 默认值
- 可选值/有效值及说明
指令文档:
- 位置要求至关重要
- 展示组合模式的交互表
- 对逃生舱口使用“谨慎使用”+“计划移除”模式
库作者指南:
- 以受众为中心的简介
- 优势/原因章节
- 分步设置指南
ESLint
ESLint
Rule Details section:
- Explain "why" not just "what"
- Focus on React's underlying assumptions
- Describe consequences of violations
Invalid/Valid sections:
- Standard intro: "Examples of [in]correct code for this rule:"
- Use X emoji for invalid, checkmark for valid
- Show inline comments explaining the violation
Configuration options:
- Show shared settings (preferred)
- Show rule-level options (backward compatibility)
- Note precedence when both exist
规则详情章节:
- 解释“为什么”而非仅“是什么”
- 聚焦于React的底层假设
- 描述违规的后果
无效/有效章节:
- 标准简介:“以下是该规则的[不]正确代码示例:”
- 无效代码使用❌表情,有效代码使用✅表情
- 展示解释违规原因的内联注释
配置选项:
- 展示共享设置(优先选择)
- 展示规则级选项(向后兼容)
- 说明两者同时存在时的优先级
Edge Cases
边缘情况
For deprecated, canary, and version-specific component patterns (placement, syntax, examples), invoke .
/docs-componentsQuick placement rules:
- after
<Deprecated>for page-level, after heading for method-level<Intro> - wrapper inline in Intro,
<Canary>in headings/props/caveats<CanaryBadge /> - Version notes use with "Starting in React 19..." pattern
<Note>
Removed APIs on index pages:
md
undefined如需了解已弃用、Canary版本和特定版本的组件模式(位置、语法、示例),请查看。
/docs-components快速位置规则:
- 在页面级弃用时放在
<Deprecated>之后,在方法级弃用时放在标题之后<Intro> - 包装器内联在Intro中,
<Canary>放在标题/属性/注意事项中<CanaryBadge /> - 版本说明使用并采用“从React 19开始...”的模式
<Note>
索引页面上的已移除API:
md
undefinedRemoved APIs {/removed-apis/}
已移除API {/removed-apis/}
These APIs were removed in React 19:
- : use
renderinstead.createRoot
Link to previous version docs (18.react.dev) for removed API documentation.
---Critical Rules
关键规则
- Heading IDs required: (lowercase, hyphens)
## Title {/*title-id*/} - Sandpack main file needs
export default - Active file syntax:
```js src/File.js active - Error headings in Troubleshooting: Use
### I'm getting an error: "[message]" {/*id*/} - Section dividers () required between headings (see Section Dividers below)
--- - InlineToc required: Always include after Intro
<InlineToc /> - Consistent parameter format: Use paramName`: description
* \optional` prefix for optional paramswith - Numbered lists for array returns: When hooks return arrays, use numbered lists in Returns section
- Generic names for returned functions: Use "set functions" not "setCount"
- Props vs Parameters: Use for Components (Type B),
#### Propsfor Hooks/APIs (Type A)#### Parameters - RSC placement: component goes before
<RSC>, not after<Intro> - Canary markers: Use wrapper inline in Intro,
<Canary>in headings/props<CanaryBadge /> - Deprecated placement: goes after
<Deprecated>for page-level, after heading for method-level<Intro> - Code comment emojis: Use X for wrong, checkmark for correct in code examples
- No consecutive Pitfalls/Notes: Combine into one component with titled subsections, or separate with prose/code (see )
/docs-components
For component heading level conventions (DeepDive, Pitfall, Note, Recipe headings), see .
/docs-components- 必须设置标题ID: (小写,连字符分隔)
## 标题 {/*title-id*/} - Sandpack主文件需要
export default - 活动文件语法:
```js src/File.js active - 问题排查中的错误标题: 使用
### 我遇到了错误:“[消息]” {/*id*/} - 必须使用章节分隔线() 分隔标题(见下方章节分隔线)
--- - 必须包含InlineToc: 始终在Intro之后包含
<InlineToc /> - 参数格式一致: 使用paramName`: 说明
* \可选`,可选参数前缀为 - 数组返回使用编号列表: 当Hook返回数组时,在返回值章节使用编号列表
- 返回函数使用通用名称: 使用“set函数”而非“setCount”
- 属性vs参数: 组件(类型B)使用,Hook/API(类型A)使用
#### 属性#### 参数 - RSC位置: 组件放在
<RSC>之前,而非之后<Intro> - Canary标记: 包装器内联在Intro中,
<Canary>放在标题/属性/注意事项中<CanaryBadge /> - Deprecated位置: 在页面级弃用时放在
<Deprecated>之后,在方法级弃用时放在标题之后<Intro> - 代码注释表情: 错误代码使用❌,正确代码使用✅
- 不要连续放置Pitfall/Note: 合并到一个带小标题的组件中,或用正文/代码分隔(查看)
/docs-components
如需了解组件标题层级约定(DeepDive、Pitfall、Note、Recipe标题),请查看。
/docs-componentsSection Dividers
章节分隔线
Use horizontal rules to visually separate major sections:
---- After - Before
<InlineToc />heading## Reference - Between API subsections - Between different function/hook definitions (e.g., between and
useState())set functions - Before - Separates API reference from examples
## Usage - Before - Separates content from troubleshooting
## Troubleshooting - Between EVERY Usage subsections - When switching to a new major use case
Always have a blank line before and after .
---使用水平分隔线可视化分隔主要章节:
---- 在之后 - 在
<InlineToc />标题之前## 参考 - 在API子章节之间 - 在不同函数/Hook定义之间(如和
useState()之间)set函数 - 在之前 - 分隔API参考和示例
## 使用场景 - 在之前 - 分隔内容和问题排查
## 问题排查 - 在每个使用场景子章节之间 - 切换到新的主要用例时
---Section ID Conventions
章节ID约定
| Section | ID Format |
|---|---|
| Main function | |
| Returned function | |
| Sub-section of returned function | |
| Troubleshooting item | |
| Pitfall | |
| Deep dive | |
| 章节 | ID格式 |
|---|---|
| 主函数 | |
| 返回的函数 | |
| 返回函数的子章节 | |
| 问题排查项 | |
| Pitfall | |
| Deep dive | |