name: react-development description: 专注于React组件开发、Hooks模式、状态管理、Context API、性能优化和现代React最佳实践的专业技能。 allowed-tools: Read, Write, Edit, Bash, Glob, Grep
React开发技能
为构建React应用程序提供专家级协助,涵盖现代模式、Hooks、状态管理和性能优化。
能力范围
- 使用TypeScript和正确类型生成React组件
- 使用组合模式实现自定义Hooks
- 配置状态管理(Context API、Redux Toolkit、Zustand)
- 通过记忆化优化渲染性能
- 使用React Testing Library设置组件测试
- 创建可访问、可复用的组件库
使用场景
在以下情况下调用此技能:
- 按照最佳实践创建新的React组件
- 为共享逻辑实现自定义Hooks
- 设置状态管理架构
- 优化组件渲染性能
- 配置React项目结构
输入参数
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
| componentName | string | 是 | 组件名称(帕斯卡命名法) |
| componentType | string | 否 | functional, class(默认:functional) |
| stateManagement | string | 否 | context, redux, zustand, jotai, none |
| typescript | boolean | 否 | 使用TypeScript(默认:true) |
| testing | boolean | 否 | 生成测试(默认:true) |
| storybook | boolean | 否 | 生成Storybook故事(默认:false) |
组件配置
{
"componentName": "UserProfile",
"componentType": "functional",
"props": [
{ "name": "user", "type": "User", "required": true },
{ "name": "onUpdate", "type": "(user: User) => void", "required": false }
],
"hooks": ["useState", "useEffect", "useCallback"],
"typescript": true,
"testing": true
}
输出结构
src/
├── components/
│ └── UserProfile/
│ ├── index.ts # 桶式导出
│ ├── UserProfile.tsx # 组件实现
│ ├── UserProfile.types.ts # 类型定义
│ ├── UserProfile.hooks.ts # 自定义Hooks
│ ├── UserProfile.styles.ts # 样式化组件或CSS模块
│ ├── UserProfile.test.tsx # 单元测试
│ └── UserProfile.stories.tsx # Storybook故事(可选)
├── hooks/
│ ├── index.ts # Hook导出
│ ├── useDebounce.ts # 防抖Hook
│ ├── useLocalStorage.ts # 本地存储Hook
│ └── useFetch.ts # 数据获取Hook
└── context/
├── index.ts # 上下文导出
└── UserContext.tsx # 用户上下文提供者
生成代码模式
函数式组件模板
import { memo, useCallback, useState } from 'react';
import type { UserProfileProps } from './UserProfile.types';
import { useUserData } from './UserProfile.hooks';
export const UserProfile = memo(function UserProfile({
user,
onUpdate,
}: UserProfileProps) {
const [isEditing, setIsEditing] = useState(false);
const { updateUser, isLoading } = useUserData();
const handleSave = useCallback(async (data: UserData) => {
await updateUser(data);
onUpdate?.(data);
setIsEditing(false);
}, [updateUser, onUpdate]);
return (
<div className="user-profile" role="region" aria-label="用户资料">
{/* 组件内容 */}
</div>
);
});
UserProfile.displayName = 'UserProfile';
自定义Hook模板
import { useState, useEffect, useCallback } from 'react';
interface UseAsyncDataOptions<T> {
initialData?: T;
onError?: (error: Error) => void;
}
export function useAsyncData<T>(
fetchFn: () => Promise<T>,
deps: unknown[] = [],
options: UseAsyncDataOptions<T> = {}
) {
const [data, setData] = useState<T | undefined>(options.initialData);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const execute = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const result = await fetchFn();
setData(result);
return result;
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
setError(error);
options.onError?.(error);
} finally {
setIsLoading(false);
}
}, deps);
useEffect(() => {
execute();
}, [execute]);
return { data, isLoading, error, refetch: execute };
}
上下文提供者模板
import {
createContext,
useContext,
useReducer,
useMemo,
type ReactNode,
} from 'react';
interface State {
user: User | null;
isAuthenticated: boolean;
}
type Action =
| { type: 'SET_USER'; payload: User }
| { type: 'LOGOUT' };
const initialState: State = {
user: null,
isAuthenticated: false,
};
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'SET_USER':
return { ...state, user: action.payload, isAuthenticated: true };
case 'LOGOUT':
return initialState;
default:
return state;
}
}
const UserContext = createContext<{
state: State;
dispatch: React.Dispatch<Action>;
} | null>(null);
export function UserProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, initialState);
const value = useMemo(() => ({ state, dispatch }), [state]);
return (
<UserContext.Provider value={value}>
{children}
</UserContext.Provider>
);
}
export function useUser() {
const context = useContext(UserContext);
if (!context) {
throw new Error('useUser必须在UserProvider内部使用');
}
return context;
}
性能优化模式
记忆化
// 记忆化昂贵计算
const sortedItems = useMemo(() =>
items.sort((a, b) => a.name.localeCompare(b.name)),
[items]
);
// 记忆化回调函数以防止子组件重新渲染
const handleClick = useCallback((id: string) => {
setSelected(id);
}, []);
// 记忆化组件
const MemoizedChild = memo(ChildComponent);
代码分割
import { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./HeavyComponent'));
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<LazyComponent />
</Suspense>
);
}
依赖项
{
"dependencies": {
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@testing-library/react": "^16.0.0",
"@testing-library/jest-dom": "^6.0.0",
"vitest": "^2.0.0"
}
}
工作流程
- 分析需求 - 确定组件结构和状态需求
- 创建类型定义 - 定义props、state和上下文类型
- 实现组件 - 使用Hooks和正确模式构建
- 添加自定义Hooks - 提取可复用逻辑
- 优化性能 - 在需要的地方应用记忆化
- 编写测试 - 组件和Hook单元测试
- 添加可访问性 - ARIA属性和键盘导航
应用的最佳实践
- TypeScript严格模式与正确类型
- 使用Hooks的函数式组件(无类组件)
- 用于共享逻辑的自定义Hooks
- 用于应用范围状态的Context API
- 用于性能的记忆化
- 正确的错误边界
- 可访问性(a11y)合规
- 使用React Testing Library进行测试
参考资料
- React文档:https://react.dev/
- React Hooks:https://react.dev/reference/react/hooks
- React Testing Library:https://testing-library.com/docs/react-testing-library/intro/
- web-artifacts-builder:https://github.com/anthropics/skills/tree/main/skills/web-artifacts-builder
- react-mcp:https://github.com/kalivaraprasad-gonapa/react-mcp
目标流程
- react-application-development
- component-library-creation
- state-management-setup
- performance-optimization
- frontend-testing