React
2026/1/15大约 2 分钟
React
核心概念
JSX
// JSX 是 JavaScript 的语法扩展
const element = <h1>Hello, {name}</h1>;
// 条件渲染
{isLoggedIn && <UserGreeting />}
{isLoggedIn ? <UserGreeting /> : <GuestGreeting />}
// 列表渲染
{items.map(item => <li key={item.id}>{item.name}</li>)}
// 样式
<div style={{ color: 'red', fontSize: 16 }}>
<div className="container">组件
// 函数组件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
// 类组件
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}Hooks
useState
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
// 函数式更新
setCount(prev => prev + 1);
// 对象状态
const [state, setState] = useState({ name: '', age: 0 });
setState(prev => ({ ...prev, name: 'Tom' }));useEffect
import { useEffect } from 'react';
function Example() {
// 每次渲染后执行
useEffect(() => {
console.log('effect');
});
// 仅挂载时执行
useEffect(() => {
console.log('mounted');
}, []);
// 依赖变化时执行
useEffect(() => {
console.log('count changed');
}, [count]);
// 清理函数
useEffect(() => {
const timer = setInterval(() => {}, 1000);
return () => clearInterval(timer); // 卸载时执行
}, []);
}useRef
import { useRef } from 'react';
function TextInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return <input ref={inputRef} />;
}
// 保存可变值(不触发重渲染)
const countRef = useRef(0);
countRef.current++;useMemo / useCallback
import { useMemo, useCallback } from 'react';
function Example({ items }) {
// 缓存计算结果
const total = useMemo(() => {
return items.reduce((sum, item) => sum + item.price, 0);
}, [items]);
// 缓存函数
const handleClick = useCallback(() => {
console.log('clicked');
}, []);
return <Child onClick={handleClick} />;
}useContext
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Child />
</ThemeContext.Provider>
);
}
function Child() {
const theme = useContext(ThemeContext);
return <div>Theme: {theme}</div>;
}useReducer
import { useReducer } from 'react';
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}自定义 Hook
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
// 使用
const [name, setName] = useLocalStorage('name', '');状态管理
Redux Toolkit
import { createSlice, configureStore } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => { state.value += 1; },
decrement: state => { state.value -= 1; },
incrementByAmount: (state, action) => {
state.value += action.payload;
}
}
});
const store = configureStore({
reducer: { counter: counterSlice.reducer }
});
// 组件中使用
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector(state => state.counter.value);
const dispatch = useDispatch();
return (
<button onClick={() => dispatch(increment())}>
{count}
</button>
);
}性能优化
React.memo
// 浅比较 props,避免不必要的重渲染
const Child = React.memo(function Child({ name }) {
return <div>{name}</div>;
});
// 自定义比较函数
const Child = React.memo(Component, (prevProps, nextProps) => {
return prevProps.id === nextProps.id;
});代码分割
import { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<Loading />}>
<LazyComponent />
</Suspense>
);
}虚拟列表
import { FixedSizeList } from 'react-window';
function VirtualList({ items }) {
return (
<FixedSizeList
height={400}
itemCount={items.length}
itemSize={50}
>
{({ index, style }) => (
<div style={style}>{items[index]}</div>
)}
</FixedSizeList>
);
}React 原理
虚拟 DOM
// React Element 结构
const element = {
type: 'div',
props: {
className: 'container',
children: [
{ type: 'span', props: { children: 'Hello' } }
]
}
};Fiber 架构
Fiber 是 React 16 引入的新协调引擎:
- 可中断的渲染
- 优先级调度
- 增量渲染
Fiber 节点结构:
- type:组件类型
- stateNode:DOM 节点
- child/sibling/return:树结构
- pendingProps/memoizedProps:props
- memoizedState:state合成事件
// React 事件是合成事件,不是原生事件
// 事件委托到 root 节点
// 跨浏览器兼容
function handleClick(e) {
e.preventDefault(); // 阻止默认行为
e.stopPropagation(); // 阻止冒泡
e.nativeEvent; // 原生事件
}