TypeScript
React 官方推荐 TypeScript。类型主要落在 Props、事件、Ref 与 Hooks 返回值上。见 组件。
函数组件 Props
type ButtonProps = {
label: string;
disabled?: boolean;
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
};
export function Button({ label, disabled, onClick }: ButtonProps) {
return (
<button type="button" disabled={disabled} onClick={onClick}>
{label}
</button>
);
}
children 常用 React.ReactNode。
带 children 的组件
type CardProps = {
title: string;
children: React.ReactNode;
};
泛型组件
type ListProps<T> = {
items: T[];
renderItem: (item: T) => React.ReactNode;
};
function List<T>({ items, renderItem }: ListProps<T>) {
return <ul>{items.map((item) => <li key={String(item)}>{renderItem(item)}</li>)}</ul>;
}
常用类型
| 类型 | 用途 |
|---|---|
React.FC | 可选;官方不强制,显式写 Props 更清晰 |
React.ComponentProps<"input"> | 继承原生 input 全部属性 |
React.ComponentPropsWithoutRef<typeof Link> | 包装第三方组件 props |
React.RefObject<HTMLDivElement> | DOM ref |
useRef
const inputRef = useRef<HTMLInputElement>(null);
inputRef.current?.focus();
事件
使用 React.ChangeEvent<HTMLInputElement> 等,避免 any。
参考文献
以下链接在编写时均可正常访问:
相关文章
渲染与协调
React 将组件渲染为虚拟 DOM 树,再协调(reconciliation)到浏览器 DOM。理解该过程有助于解释 key、memo 与性能优化。涵盖渲染流程、Fiber、startTransition、Suspense、最佳实践与常见坑。
工程化
新建 React 项目时,官方与社区主流工具为 Vite;全栈场景常用 Next.js。涵盖 Vite + React、Create React App 现状、Next.js、目录结构、环境变量、部署、最佳实践与常见坑。
测试
React 组件测试推荐 React Testing Library(RTL):从用户可见行为断言,而非实现细节。运行器常用 Vitest 或 Jest。涵盖安装配置、查询优先级、异步测试、Mock 网络请求、最佳实践与常见坑。
构建与分包
通过代码分割与构建配置减小首屏 JavaScript 体积。涵盖 React.lazy/Suspense、路由级分割、Tree Shaking、Vite 生产构建、体积分析、最佳实践与常见坑。运行时优化见 runtime。
Effect 与副作用
useEffect 用于在组件渲染后执行与外部系统同步的逻辑(请求、订阅、手动改 DOM 等)。涵盖基本用法、依赖数组、适用/不适用场景、useLayoutEffect、最佳实践与常见坑。
状态管理
React 组件内 state 用 Hooks;跨组件共享状态可选 Context、Redux Toolkit、Zustand 等。见 Context Hook。
Series
react
16 / 16