跳到主内容
智客 ZICQ

技能库 智客分类:Agent 工作流 react

React

反应18+框架护栏,模式,以及AI辅助开发的最佳做法. 与 React 项目(.jsx/.tsx文件)合作时使用,或用户提及React时使用. 提供组件模式,钩子,状态管理,测试,和性能指导.

10 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

反应18+框架护栏、模式以及AI协助发展的最佳做法

何时用

与 React 工程(.jsx/.tsx 文件)合作,或当用户提及 React 时. 提供组件模式、钩子、国家管理、测试和业绩准则

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:React Guide、Core Principles、Guardrails、Component Rules、Hooks Rules、State Management。

文件分析

文件分析:除 SKILL.md 外,正文引用了 references/patterns.md,属于带资源的技能包,这些文件按需再读。

官方 description(原文)

React 18+ framework guardrails, patterns, and best practices for AI-assisted development. Use when working with React projects (.jsx/.tsx files), or when the user mentions React. Provides component patterns, hooks, state management, testing, and performance guidelines.

React GuideCore PrinciplesGuardrailsComponent RulesHooks RulesState ManagementPerformanceFile NamingProject StructureComponent PatternsFunctional Component with PropsComponent with Children

· 许可:MIT

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
react
description
React 18+ framework guardrails, patterns, and best practices for AI-assisted development. Use when working with React projects (.jsx/.tsx files), or when the user mentions React. Provides component patterns, hooks, state management, testing, and performance guidelines.
许可
MIT
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。
指令中引用的文件 · 1
  • references/patterns.md

以下路径提取自原文;文件是否齐全请以来源仓库中的完整目录为准。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

该技能引用了附属文件,请从来源获取完整目录;仅复制 SKILL.md 可能缺少依赖。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「react」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-4245c33afac68a56-%E5%8F%8D%E5%BA%94.html
请存为 .cursor/skills/react/SKILL.md 或 .claude/skills/react/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。
该技能还带 scripts/、references/、assets/ 等文件,请从 https://github.com/ar4mirez/samuel 取完整目录,不要只建一个 SKILL.md。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/ar4mirez/samuel' --list

npx skills add 'https://github.com/ar4mirez/samuel' --skill 'react'

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版
--- name: react description: | React 18+ framework guardrails, patterns, and best practices for AI-assisted development. Use when working with React projects (.jsx/.tsx files), or when the user mentions React. Provides component patterns, hooks, state management, testing, and performance guidelines. license: MIT metadata: author: samuel version: "1.0" category: framework language: typescript extensions: ".jsx,.tsx" --- # React Guide > Applies to: React 18+, TypeScript, Single Page Applications, Component Libraries, Web Apps ## Core Principles 1. **Component-Based**: Build encapsulated components that manage their own state 2. **Declarative**: Describe what UI should look like, React handles DOM updates 3. **Unidirectional Data Flow**: Props down, callbacks up 4. **Composition Over Inheritance**: Prefer component composition and custom hooks 5. **TypeScript First**: All components use TypeScript with strict prop interfaces ## Guardrails ### Component Rules - Use functional components exclusively (no class components) - Keep components under 200 lines (split into smaller components) - Every component has a TypeScript interface for props - Use `React.ReactNode` for children props, not `JSX.Element` - Implement error boundaries for graceful error handling - Use proper accessibility attributes (ARIA roles, labels, keyboard navigation) - Co-locate component, styles, and tests in the same directory ### Hooks Rules - Only call hooks at the top level (never inside conditions, loops, or nested functions) - Only call hooks from React function components or custom hooks - Name custom hooks with `use` prefix: `useAuth`, `useQuery`, `useFetch` - Always include all dependencies in `useEffect` / `useMemo` / `useCallback` arrays - Clean up side effects in `useEffect` return function - Prefer `useReducer` over `useState` for complex state logic - Use ESLint `react-hooks` plugin to enforce rules ### State Management - Local state: `useState` for simple, `useReducer` for complex - Shared state: Context API for low-frequency updates (theme, auth, locale) - Server state: TanStack Query (React Query) for data fetching and caching - Global client state: Zustand for complex cross-component state - Avoid prop drilling beyond 2 levels (use composition or context) - Never store derived state (compute it during render) ### Performance - Use `React.memo()` only for expensive pure components (measure first) - Use `useMemo` for expensive computations, `useCallback` for stable references - Lazy load routes and heavy components with `React.lazy()` + `Suspense` - Virtualize long lists (react-window, @tanstack/virtual) - Keep bundle under 200KB initial load (code-split aggressively) - Avoid anonymous functions in JSX for frequently re-rendered components ### File Naming - Components: `PascalCase.tsx` (e.g., `UserCard.tsx`) - Hooks: `camelCase.ts` with `use` prefix (e.g., `useAuth.ts`) - Utils: `camelCase.ts` (e.g., `formatDate.ts`) - Types: `camelCase.ts` or `types.ts` per feature - Tests: `*.test.tsx` or `*.spec.tsx` (co-located) - Styles: `*.module.css` or `*.styles.ts` (co-located) ## Project Structure ``` my-app/ ├── public/ │ └── index.html ├── src/ │ ├── assets/ # Static assets (images, fonts) │ ├── components/ # Reusable components │ │ ├── ui/ # Base UI components (Button, Input, Modal) │ │ └── features/ # Feature-specific components │ ├── hooks/ # Custom hooks │ ├── contexts/ # React contexts │ ├── services/ # API services │ ├── utils/ # Utility functions │ ├── types/ # TypeScript types │ ├── pages/ # Page components (route-level) │ ├── App.tsx │ ├── main.tsx │ └── index.css ├── tests/ ├── package.json ├── tsconfig.json ├── vite.config.ts └── README.md ``` - `components/ui/` for reusable design system primitives - `components/features/` for domain-specific compositions - `hooks/` for shared custom hooks (feature-specific hooks co-locate with component) - `contexts/` for React context providers - `services/` for API layer (fetch wrappers, API clients) - `pages/` for route-level components only ## Component Patterns ### Functional Component with Props ```tsx interface UserCardProps { userId: string; onSelect?: (user: User) => void; className?: string; } export function UserCard({ userId, onSelect, className }: UserCardProps) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchUser = async () => { try { const data = await userService.getById(userId); setUser(data); } finally { setLoading(false); } }; fetchUser(); }, [userId]); if (loading) return ; if (!user) return null; return (
onSelect?.(user)}>

{user.name}

{user.email}

); } ``` ### Component with Children ```tsx interface CardProps { title: string; children: React.ReactNode; footer?: React.ReactNode; } export function Card({ title, children, footer }: CardProps) { return (

{title}

{children}
{footer &&
{footer}
}
); } ``` ## State Management Patterns ### Context API (Auth, Theme, Locale) ```tsx interface AuthContextValue { user: User | null; login: (credentials: LoginCredentials) => Promise; logout: () => void; isAuthenticated: boolean; } const AuthContext = createContext(null); export function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState(null); const login = async (credentials: LoginCredentials) => { const user = await authService.login(credentials); setUser(user); }; const logout = () => { authService.logout(); setUser(null); }; return ( {children} ); } export function useAuth() { const context = useContext(AuthContext); if (!context) throw new Error('useAuth must be used within AuthProvider'); return context; } ``` ### TanStack Query (Server State) ```tsx import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; function useUsers() { return useQuery({ queryKey: ['users'], queryFn: () => userService.getAll(), staleTime: 5 * 60 * 1000, }); } function useCreateUser() { const queryClient = useQueryClient(); return useMutation({ mutationFn: (data: CreateUserDTO) => userService.create(data), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['users'] }); }, }); } ``` ### Zustand (Complex Client State) ```tsx import { create } from 'zustand'; interface CartStore { items: CartItem[]; addItem: (item: CartItem) => void; removeItem: (id: string) => void; clearCart: () => void; total: () => number; } const useCartStore = create()((set, get) => ({ items: [], addItem: (item) => set((state) => ({ items: [...state.items, item] })), removeItem: (id) => set((state) => ({ items: state.items.filter((item) => item.id !== id), })), clearCart: () => set({ items: [] }), total: () => get().items.reduce((sum, item) => sum + item.price * item.quantity, 0), })); ``` ## Routing (React Router v6) ```tsx import { createBrowserRouter, RouterProvider } from 'react-router-dom'; import { lazy, Suspense } from 'react'; const Dashboard = lazy(() => import('./pages/Dashboard')); const Settings = lazy(() => import('./pages/Settings')); const router = createBrowserRouter([ { path: '/', element: , children: [ { index: true, element: }, { path: 'dashboard', element: }, { path: 'settings', element: }, { path: '*', element: }, ], }, ]); function App() { return ( }> ); } ``` ## Forms (React Hook Form + Zod) ```tsx import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; const userSchema = z.object({ email: z.string().email('Invalid email'), password: z.string().min(8, 'Password must be at least 8 characters'), name: z.string().min(2, 'Name is required'), }); type UserFormData = z.infer; function UserForm({ onSubmit }: { onSubmit: (data: UserFormData) => void }) { const { register, handleSubmit, formState: { errors, isSubmitting }, reset, } = useForm({ resolver: zodResolver(userSchema) }); const handleFormSubmit = async (data: UserFormData) => { await onSubmit(data); reset(); }; return (
Email {errors.email && {errors.email.message}}
{isSubmitting ? 'Submitting...' : 'Submit'} ); } ``` ## Testing Overview ### Standards - Use React Testing Library (`@testing-library/react`) for component tests - Use `userEvent` over `fireEvent` for realistic user interactions - Test behavior, not implementation details - Query by accessible roles and labels first (not test IDs) - Mock API calls, not internal component state - Coverage target: >80% for business logic components ### Basic Component Test ```tsx import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; describe('UserCard', () => { it('renders user information', () => { render(); expect(screen.getByText('John Doe')).toBeInTheDocument(); }); it('calls onSelect when clicked', async () => { const onSelect = vi.fn(); render(); await userEvent.click(screen.getByRole('button')); expect(onSelect).toHaveBeenCalledWith(mockUser); }); }); ``` ## Tooling ### Essential Commands ```bash npm create vite@latest my-app -- --template react-ts # New project npm install # Install deps npm run dev # Dev server npm run build # Production build npm run lint # ESLint npm test # Run tests npm run test:cov # Coverage ``` ### Recommended Dependencies ```json { "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.x", "@tanstack/react-query": "^5.x", "zustand": "^4.x", "react-hook-form": "^7.x", "zod": "^3.x", "@hookform/resolvers": "^3.x" }, "devDependencies": { "@types/react": "^18.x", "@types/react-dom": "^18.x", "@testing-library/react": "^14.x", "@testing-library/user-event": "^14.x", "vitest": "^1.x", "eslint-plugin-react-hooks": "^4.x" } } ``` ### ESLint Configuration ```json { "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:react/recommended", "plugin:react-hooks/recommended" ], "rules": { "react/react-in-jsx-scope": "off", "react/prop-types": "off", "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "warn" } } ``` ## Advanced Topics For detailed patterns and examples, see: - [references/patterns.md](references/patterns.md) -- Compound components, custom hooks, testing, performance, security patterns ## External References - [React Documentation](https://react.dev/) - [React TypeScript Cheatsheet](https://react-typescript-cheatsheet.netlify.app/) - [TanStack Query](https://tanstack.com/query/latest) - [Zustand](https://zustand-demo.pmnd.rs/) - [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/) - [React Hook Form](https://react-hook-form.com/) - [Zod](https://zod.dev/)

相关技能

Agent 工作流

Skill Creator

创造有效技能指南。 当用户想创造出新的技能(或更新现有的技能),以专业知识,工作流程,或工具集成来扩展克洛德的能力时,应该使用这种技能.

Agent 工作流

Clawdhub

使用ClawdHub CLI搜索,安装,更新并发布从taladhub.com的代理技能. 需要获取苍蝇上的新技能时使用,将安装的技能同步到最新版本或特定版本,或者发布 npm-instainddhub CLI 的新/更新的技能文件夹.

Agent 工作流

Agent Team Orchestration

管弦乐团多代理团队,任务设定周期,交接协议,审查工作流程. 使用时间: (1)建立2+特派员队伍,具有不同专业,(2)确定任务路线和生命周期(收录框_ spec_建设_审查_完成),(3)在特派员之间制定交接协议,(4)建立审查和质量关口,(5)管理特派员之间的交流和文物共享.

Agent 工作流

Superpowers

Spec-first,TDD,子代理驱动的软件开发工作流程. 当:(1)构建任何新功能或应用——触发脑暴_计划_子代理执行回路,(2)调试出一个bug或测试失败——触发系统性的根起过程,(3)用户说"让我们构建","帮助我计划","我想添加X",或"这个被打破",(4)完成一个功…