SuperAPI AI 工具集

react-dev

编程与开发

查看项目

更新于 10-15 18:20

技能介绍

本技能用于在 TypeScript 环境下构建 React 组件时提供类型安全方面的指导。其核心理念是“类型安全的 React = 编译期保证 = 有信心的重构”。\n\n适用场景:构建带类型的 React 组件、实现泛型组件、为事件处理器/表单/refs 标注类型、使用 React 19 特性(Actions、Server Components、use())、集成路由(TanStack Router、React Router)、编写具备正确类型的自定义 Hook。不适用于:非 React 的 TypeScript、原生 JS 的 React。\n\nReact 19 变更:涉及破坏性变更与迁移。ref 作为 prop(forwardRef 已废弃);useActionState 取代 useFormState;use() 用于解包 promise/context(会挂起直至解析)。\n\n组件模式:通过 ComponentPropsWithoutRef 扩展原生元素;children 可用 React.ReactNode(任意可渲染内容)、React.ReactElement(单个元素)或 render prop 函数;变体 Props 可用可辨识联合(discriminated unions)。\n\n事件处理器:使用具体事件类型以获得准确的目标类型,如 MouseEvent、FormEvent、ChangeEvent、KeyboardEvent。\n\nHook 类型:useState 对联合类型/null 显式标注;useRef 对 DOM 用 null、对可变值用初值;useReducer 用可辨识联合表示 action;自定义 Hook 返回值用 as const;useContext 用 null 守卫模式。\n\n泛型组件:类型从 props 推断,调用处无需手动标注;使用 keyof T 表示列键、render props 实现自定义渲染;可用约束泛型(如 T extends HasId)要求特定属性。\n\nServer Components:在服务端运行,可为 async;Server Actions 使用 'use server' 进行变更;客户端可用 useActionState 配合 Server Action;use() 用于 promise 交接(服务端传未 await 的 promise,客户端用 use() 解包)。\n\n路由:TanStack Router 提供编译期类型安全并支持 Zod 校验;React Router v7 在 Framework Mode 下自动生成类型。\n\n应始终遵循:使用具体事件类型;对联合/null 显式标注 useState;用 ComponentPropsWithoutRef 扩展原生元素;变体 Props 用可辨识联合;元组返回用 as const;React 19 用 ref as prop(不用 forwardRef);表单动作用 useActionState;使用类型安全路由模式。\n\n应避免:事件处理器用 any;children 用 JSX.Element(应用 ReactNode);React 19+ 使用 forwardRef;使用已废弃的 useFormState;忽略 DOM ref 的 null 处理;在同一文件混用 Server/Client 组件;把 promise 传给 use() 时先 await。\n\n技能还包含若干参考文档:hooks.md、event-handlers.md、react-19-patterns.md、generic-components.md、server-components.md、tanstack-router.md、react-router.md。