关于 react
react 是面向 React UI 开发的技能,涵盖组件、状态、路由和性能优化,适用于构建与维护 React 应用。它以函数组件和 Hooks 为主要代码模式,并列出组件组织与副作用处理的实践。
主要功能
- 01编写 React 组件与 JSX
- 02使用 Hooks 管理状态和生命周期
- 03构建可复用组件与自定义 Hook
- 04应用 Context 或状态管理库
- 05配置路由并优化渲染性能
适用场景
- 01搭建 Vite 或 Create React App 项目
- 02实现带状态的界面组件
- 03为应用添加 React Router 路由
- 04优化大型路由的加载与渲染
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ partme-ai/ full-stack-skills --skill react安装后在 Claude Code 中输入/react确认已加载。
附带文件LICENSE.txt
详细介绍
适用场景
当用户希望进行以下操作时,请使用此技能:
- 使用 React 组件和 JSX 构建用户界面
- 使用 hooks 管理组件状态和生命周期
- 创建可复用、可组合的 React 组件
- 使用 Context API 或状态管理库(Redux、Zustand)
- 使用 Vite 或 Create React App 搭建 React 项目
- 使用 React Router 实现路由
- 优化渲染性能(React.memo、useMemo、懒加载)
使用方法
工作流
- 识别请求领域(组件创建、状态管理、路由、性能等)
- 遵循官方文档模式,采用 React 最佳实践
- 使用函数组件和 hooks 生成 JSX/TSX 代码
- 验证组件树能否正确渲染,以及状态流转是否清晰
1. 函数组件
import { useState } from 'react';
interface UserCardProps {
name: string;
email: string;
onSelect: (name: string) => void;
}
export function UserCard({ name, email, onSelect }: UserCardProps) {
return (
<div className="user-card" onClick={() => onSelect(name)}>
<h3>{name}</h3>
<p>{email}</p>
</div>
);
}
2. 状态和副作用
import { useState, useEffect } from 'react';
export function UserList() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('/api/users')
.then(res => res.json())
.then(data => {
setUsers(data);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
3. 自定义 Hook
import { useState, useCallback } from 'react';
function useToggle(initial = false): [boolean, () => void] {
const [value, setValue] = useState(initial);
const toggle = useCallback(() => setValue(v => !v), []);
return [value, toggle];
}
4. Context 模式
import { createContext, useContext, useState, ReactNode } from 'react';
const ThemeContext = createContext<{ dark: boolean; toggle: () => void } | null>(null);
export function ThemeProvider({ children }: { children: ReactNode }) {
const [dark, setDark] = useState(false);
const toggle = () => setDark(d => !d);
return <ThemeContext.Provider value={{ dark, toggle }}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('useTheme must be used within ThemeProvider');
return ctx;
}
最佳实践
- 让组件保持精简,并专注于单一职责
- 将状态提升到最近的共同祖先;对于深层共享状态,使用 Context
- 渲染列表时,始终提供稳定的
key属性 - 在
useEffect的返回函数中清理副作用(订阅、定时器) - 避免在 JSX 中内联创建新对象或函数,以防不必要的重新渲染
- 使用
React.lazy和Suspense对大型路由进行代码拆分
资源
- 官方文档:https://react.dev/
- React hooks 参考:https://react.dev/reference/react
- Create React App:https://create-react-app.dev/
关键词
react、React Hooks、JSX、TSX、组件、状态、props、useEffect、useState、Context API、函数组件、性能、memo、懒加载
评论
支持 Markdown