React 知识速查表
本页面汇总了 React 编程中最常用的语法和知识点,方便快速查阅。
核心概念
| 概念 | 说明 |
|---|---|
| 组件 | UI 的独立可复用构建块 |
| JSX | JavaScript 的语法扩展,用于描述 UI |
| Props | 父组件传递给子组件的数据 |
| State | 组件内部的响应式数据 |
| 虚拟 DOM | React 维护的轻量 DOM 副本 |
组件创建
// 函数组件(推荐)
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// 箭头函数组件
const Welcome = (props) => <h1>Hello, {props.name}!</h1>;
常用 Hooks
useState
const [state, setState] = useState(initialValue);
setState(newValue); // 直接设置
setState(prev => prev + 1); // 函数式更新
useEffect
useEffect(() => {
// 副作用逻辑
return () => {}; // 清理函数
}, [dependencies]); // 依赖数组
useContext
const value = useContext(MyContext);
useRef
const ref = useRef(initialValue);
ref.current // 访问或修改值
useMemo / useCallback
const value = useMemo(() => compute(), [deps]);
const fn = useCallback(() => {}, [deps]);
条件渲染
// 三元运算符
{isLoggedIn ? <User /> : <Login />}
// 逻辑与 &&
{show && <Component />}
// switch
{status === 'loading' && <Loading />}
{status === 'error' && <Error />}
{status === 'success' && <Success />}
列表渲染
function List({ items }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
事件处理
function Button() {
const handleClick = (e) => {
e.preventDefault();
console.log('点击');
};
return <button onClick={handleClick}>点击</button>;
}
表单处理
function Form() {
const [value, setValue] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(value);
};
return (
<form onSubmit={handleSubmit}>
<input
value={value}
onChange={e => setValue(e.target.value)}
/>
<button type="submit">提交</button>
</form>
);
}
常用 API
| API | 说明 |
|---|---|
React.createElement() | 创建 React 元素 |
React.Component | 类组件基类 |
React.Fragment | 片段,避免额外 DOM 节点 |
React.memo() | 高阶组件,记忆组件 |
React.useImperativeHandle() | 暴露实例方法 |
React.forwardRef() | 转发 ref |
生命周期(类组件)
| 阶段 | 方法 |
|---|---|
| 挂载 | constructor, render, componentDidMount |
| 更新 | render, componentDidUpdate |
| 卸载 | componentWillUnmount |
状态管理方案
| 方案 | 适用场景 |
|---|---|
| useState | 局部状态 |
| useContext | 全局状态 |
| useReducer | 复杂状态逻辑 |
| Redux | 大型应用 |
| Zustand | 轻量级状态管理 |
| Jotai | 原子化状态 |
React Router
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
性能优化
- 使用
React.memo()避免不必要的重渲染 - 使用
useMemo()缓存计算结果 - 使用
useCallback()缓存函数 - 使用
key帮助 React 识别元素 - 代码分割(React.lazy)
CSS 方案
| 方案 | 说明 |
|---|---|
| CSS Modules | 模块化 CSS |
| Styled Components | CSS-in-JS |
| Tailwind CSS | Utility-First CSS |
| CSS-in-JS | 内联样式对象 |
常用库
| 库 | 用途 |
|---|---|
| react-router-dom | 路由 |
| axios | HTTP 请求 |
| redux | 状态管理 |
| react-query | 服务端状态管理 |
| formik / react-hook-form | 表单处理 |