以下是针对 React 新手的 从零开始完整指南,包含基础概念、开发流程和实用案例:
一、环境搭建(5分钟)
bash
复制
1. 安装 Node.js(含 npm)
访问 https://nodejs.org 下载 LTS 版本
2. 创建 React 项目
npx create-react-app my-first-app
3. 启动开发服务器
cd my-first-app
npm start
二、核心概念速记
概念 说明 对比 Vue
JSX 允许在 JS 中写 HTML 模板 类似 Vue 的 template
组件 函数组件 / 类组件 类似 Vue 的 SFC
Props 父组件向子组件传值 类似 Vue 的 props
State 组件内部状态管理 类似 Vue 的 data
Hooks 函数组件管理状态的新方式 类似 Composition API
三、实战案例:TodoList 应用
- 组件结构规划
bash
复制
src/
components/
TodoForm.js # 添加任务表单
TodoItem.js # 单个任务项
App.js # 主组件 - 基础组件代码
App.js (主组件)
jsx
复制
import { useState } from ‘react’;
import TodoForm from ‘./components/TodoForm’;
import TodoItem from ‘./components/TodoItem’;
function App() {
const [todos, setTodos] = useState([
{ id: 1, text: ‘学习 React’, completed: false },
{ id: 2, text: ‘写 TodoList’, completed: true }
]);
const addTodo = (text) => {
setTodos([…todos, { id: Date.now(), text, completed: false }]);
};
const toggleTodo = (id) => {
setTodos(todos.map(todo =>
todo.id === id ? { …todo, completed: !todo.completed } : todo
));
};
return (
Todo List ({todos.length})
{todos.map(todo => (
))}
);
}
export default App;
components/TodoForm.js
jsx
复制
import { useState } from ‘react’;
export default function TodoForm({ onAdd }) {
const [inputText, setInputText] = useState(‘’);
const handleSubmit = (e) => {
e.preventDefault();
if (inputText.trim()) {
onAdd(inputText);
setInputText(‘’);
}
};
return (
<input
type=“text”
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder=“输入新任务…”
/>
添加
);
}
components/TodoItem.js
jsx
复制
export default function TodoItem({ todo, onToggle }) {
return (
<li
style={{
textDecoration: todo.completed ? ‘line-through’ : ‘none’,
color: todo.completed ? ‘#666’ : ‘#000’
}}
onClick={() => onToggle(todo.id)}
>
{todo.text}
);
}
四、关键知识点解析
- 状态管理(useState Hook)
jsx
复制
// 声明状态
const [count, setCount] = useState(0);
// 修改状态
<button onClick={() => setCount(count + 1)}>
点击次数: {count}
2. 生命周期(useEffect Hook)
jsx
复制
useEffect(() => {
// 组件挂载时执行
console.log(‘组件加载完成’);
return () => {
// 组件卸载时执行
console.log(‘组件即将卸载’);
};
}, []); // 空数组表示只运行一次
3. 条件渲染
jsx
复制
{isLoading ? (
) : (
)}
五、调试技巧
React DevTools 浏览器扩展
查看组件树结构
实时编辑 Props/State
错误边界(Error Boundaries)
jsx
复制
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return
Something went wrong.
;}
return this.props.children;
}
}
六、项目优化建议
代码分割
jsx
复制
const OtherComponent = React.lazy(() => import(‘./OtherComponent’));
function MyComponent() {
return (
<React.Suspense fallback={
</React.Suspense>
);
}
性能优化
jsx
复制
// 使用 React.memo 缓存组件
const MemoizedComponent = React.memo(MyComponent);
// 使用 useCallback 缓存函数
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
七、学习资源推荐
官方文档:https://react.dev
中文社区:https://react.gg
实战项目:https://github.com/piotrwitek/react-redux-typescript-guide
通过这个 TodoList 案例,你可以掌握 React 的核心开发模式。接下来可以尝试:
添加本地存储功能(localStorage)
实现分类过滤功能
集成 React Router 实现多页面
使用 Redux/Toolkit 管理复杂状态