React 速查表
可搜索、可打印的 React 19 参考手册——组件、JSX、Hooks、全新的 Actions API、上下文、引用以及性能优化。免费。
组件与 JSX
12function App() { return <h1>Hi</h1>; }
返回 JSX 的函数组件
export default function App() {}
默认导出组件
<Greeting name="Ada" />
用 props 渲染组件
{1 + 2} or {user.name}
用花括号嵌入 JS 表达式
<>{a}{b}</>
Fragment 分组节点,无额外 DOM
<div className="card">
CSS 用 className 而非 class
{isOpen && <Menu />}
用 && 条件渲染
{ok ? <Yes /> : <No />}
用三元运算在节点间选择
{items.map(i => <li key={i.id}>{i.t}</li>)}
从数组渲染列表
function Btn({ label, onClick }) {}
在签名中解构 props
function Card({ children }) { return children; }
通过 children prop 读取嵌套 JSX
<input value={v} onChange={onChange} />
绑定到 state 的受控输入
渲染与初始化
10import { createRoot } from 'react-dom/client'
导入客户端 root API
createRoot(document.getElementById('root')).render(<App/>)
将应用挂载到 DOM
import { StrictMode } from 'react'
导入 StrictMode 包装器
<StrictMode><App /></StrictMode>
在开发中暴露 bug
import { hydrateRoot } from 'react-dom/client'
导入水合 API
hydrateRoot(el, <App />)
将 React 附加到服务端 HTML
root.unmount()
卸载已挂载的 root
import App from './App.jsx'
从模块导入组件
<App {...props} />
将对象展开为 props
export { Button, Card }
命名导出多个组件
状态与副作用
12const [count, setCount] = useState(0)
声明状态变量
setCount(c => c + 1)
基于先前值更新
setUser(u => ({ ...u, name }))
以不可变方式更新对象状态
useEffect(() => { run(); }, [dep])
依赖变化时运行副作用
useEffect(() => { /* once */ }, [])
仅在挂载时运行副作用
useEffect(() => () => cleanup(), [])
返回清理函数
const ref = useRef(null)
跨渲染保存可变值
const [state, dispatch] = useReducer(r, init)
用 reducer 管理复杂状态
const theme = useContext(ThemeContext)
读取最近的 context 值
const memo = useMemo(() => calc(a), [a])
记忆化昂贵的计算
useLayoutEffect(() => {}, [])
在布局后同步运行
useSyncExternalStore(sub, get)
订阅外部 store
React 19 hook 与 API
12import { use } from 'react'
导入新的 use API
const data = use(promise)
读取 promise,就绪前挂起
const theme = use(ThemeContext)
读取 context,允许有条件使用
const [state, action, pending] = useActionState(fn, init)
追踪 state、action 和 pending
const [opt, addOpt] = useOptimistic(state, reducer)
即时显示乐观值
const { pending } = useFormStatus()
读取父表单的提交状态
const [isPending, startTransition] = useTransition()
将更新标记为非紧急
startTransition(async () => await save())
在 transition 中运行异步 Action
const deferred = useDeferredValue(value)
延迟某值以保持 UI 响应
const id = useId()
生成稳定的唯一 id
<title>Page title</title>
在树中任意位置渲染元数据
function Input({ ref }) {}
ref 是普通 prop,无需 forwardRef
表单与 Action
12<form action={handleSubmit}>
将函数作为表单 Action 传递
function handleSubmit(formData) {}
Action 接收 FormData
formData.get('email')
从 FormData 读取字段
const [state, action] = useActionState(submit, null)
将 Action 接入组件状态
<form action={action}>
在表单上使用包装后的 Action
const [s, a, pending] = useActionState(fn, init)
为 UI 暴露 pending 标志
return { error: 'Invalid' }
从 Action 返回错误状态
function Submit() { const { pending } = useFormStatus() }
在提交按钮内读取 pending
<button disabled={pending}>Save</button>
pending 时禁用提交
import { requestFormReset } from 'react-dom'
导入表单重置辅助函数
requestFormReset(formEl)
重置非受控表单
<form action={action}><Submit /></form>
将 Action 表单与状态组合
Props 与组合
10function Hi({ name = 'Guest' }) {}
通过解构设置默认 prop
function Box({ children }) { return children; }
用 children prop 包裹内容
<Box><p>Inside</p></Box>
将 JSX 作为 children 传递
function List({ render }) { return render(); }
render prop 模式
<List render={() => <Item />} />
提供渲染函数
<Input {...props} />
用展开转发所有 props
const { id, ...rest } = props
取一个 prop 并传递其余
<Avatar {...rest} size="lg" />
先展开再覆盖某个 prop
function Btn(props: BtnProps) {}
用 TypeScript 接口为 props 定义类型
<Slot label={<b>Hi</b>} />
通过命名 prop 传递 JSX
事件
10<button onClick={handleClick}>
绑定点击处理器
function handleClick(e) {}
接收合成事件
<input onChange={e => set(e.target.value)} />
在 change 时读取输入值
<form onSubmit={e => e.preventDefault()}>
阻止默认表单提交
e.stopPropagation()
阻止事件冒泡
<li onClick={() => remove(id)}>
用闭包传递参数
<input onKeyDown={e => e.key === 'Enter'}
处理特定按键
<div onMouseEnter={hover}>
监听指针事件
e.currentTarget.value
读取处理器所在的元素
<button onClick={() => {}} type="button">
避免隐式表单提交
列表与 key
10arr.map(x => <li key={x.id}>{x.t}</li>)
每项渲染一个节点
key={item.id}
为每项赋予稳定的 key
key={index}
索引 key 仅用于静态列表
users.map(u => <Card key={u.id} {...u} />)
将项字段展开为 props
{list.length === 0 && <Empty />}
为空列表显示回退内容
import { Fragment } from 'react'
为带 key 的分组导入 Fragment
<Fragment key={id}>{a}{b}</Fragment>
列表中带 key 的 fragment
{rows.filter(r => r.on).map(...)}
映射前先筛选
Keys must be unique among siblings
key 为何帮助 React 比对列表
{[...Array(n)].map((_, i) => ...)}
映射固定长度的范围
Context
10const ThemeContext = createContext('light')
创建带默认值的 context
import { createContext } from 'react'
导入 context 工厂
<ThemeContext value={theme}>
提供值(React 19 语法)
<ThemeContext value={theme}><App /></ThemeContext>
包裹读取它的子树
const theme = useContext(ThemeContext)
用 useContext 读取 context
const theme = use(ThemeContext)
用 use API 读取 context
if (cond) { const t = use(Ctx); }
use 可有条件读取 context
export const ThemeContext = createContext()
导出共享的 context
<Ctx value={{ user, setUser }}>
将对象作为值传递
Avoid new objects each render
记忆化值以限制重渲染
Ref
10const inputRef = useRef(null)
创建 ref 持有者
<input ref={inputRef} />
将 ref 附加到节点
inputRef.current.focus()
通过 current 访问 DOM 节点
function Field({ ref }) { return <input ref={ref} /> }
ref 作为 prop,无需 forwardRef
<Field ref={inputRef} />
将 ref 传递给组件
useImperativeHandle(ref, () => ({ focus }))
暴露命令式 API
const setRef = node => { box = node; }
使用回调 ref
<div ref={setRef} />
附加回调 ref
const count = useRef(0)
存储值而不触发重渲染
ref={node => { return () => cleanup(); }}
带清理的回调 ref(React 19)
性能
10const Memo = memo(Component)
props 相等时跳过重渲染
import { memo } from 'react'
导入 memo 辅助函数
const value = useMemo(() => calc(a), [a])
缓存计算值
const fn = useCallback(() => f(a), [a])
缓存函数标识
const Lazy = lazy(() => import('./Big.jsx'))
对组件进行代码分割
import { lazy, Suspense } from 'react'
导入 lazy 和 Suspense
<Suspense fallback={<Spin />}><Lazy /></Suspense>
加载时显示回退内容
startTransition(() => setQuery(q))
标记非紧急的状态更新
const slow = useDeferredValue(query)
延迟昂贵的派生 UI
React Compiler auto-memoizes
通常可省去手动记忆化
杂项与元数据
10<Suspense fallback={<Loading />}>
异步内容的边界
class ErrorBoundary extends Component {}
捕获渲染错误(旧式类组件)
<title>My Page</title>
从组件提升文档标题
<meta name="description" content="..." />
将 meta 标签渲染到 head 中
<link rel="stylesheet" href="..." />
提升样式表链接
<Comp key={id} />
更改 key 以重新挂载组件
React.lazy(() => import('./Page.jsx'))
懒加载导入路由组件
createPortal(node, container)
渲染到不同的 DOM 节点
{/* a comment */}
在 JSX 内编写注释
cleanup return in useEffect
始终释放订阅/定时器
没有条目匹配“:q”。
需要帮助?
使用此工具时遇到问题?请告诉我们的团队。