JSX 基础
表达式与属性
const name = "Alice"; const el =

Hello, {name}!

; const img = photo;
JSX 规则
{expression}嵌入任意 JS 表达式
className替代 HTML 的 class
htmlFor替代 HTML 的 for
style={{color: 'red'}}内联样式,值为对象
<Component />自闭合标签(必须)
<> ... </>Fragment(不产生额外 DOM 节点)
组件
函数组件
function Greeting({ name }) { return

Hello, {name}!

; } // Arrow function variant const Greeting = ({ name }) => (

Hello, {name}!

);
Props
function Card({ title, children }) { return (

{title}

{children}
); }

Content here

默认 Props
function Button({ label = "Click me", onClick }) { return ; }
状态(useState)
基础状态
import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( ); }
函数式更新
setCount(prev => prev + 1); // use prev state setItems(prev => [...prev, newItem]); // arrays setUser(prev => ({...prev, name: "Bob"})); // objects
状态规则
Immutable updates永远不要直接修改 state
Async batching更新可能被批量合并
Functional form依赖上一个 state 时,使用 prev => 形式
副作用(useEffect)
副作用模式
import { useEffect } from "react"; // Run on every render useEffect(() => { /* ... */ }); // Run once on mount useEffect(() => { /* ... */ }, []); // Run when deps change useEffect(() => { /* ... */ }, [count]); // Cleanup on unmount useEffect(() => { const id = setInterval(tick, 1000); return () => clearInterval(id); }, []);
列表与 Key
function TodoList({ items }) { return ( ); }

key 必须是稳定的唯一 ID,避免使用数组索引作为 key

事件处理
事件绑定
setVal(e.target.value)} />
{ e.preventDefault(); handleSubmit(); }}>
常用事件
onClick鼠标点击
onChange输入值变化
onSubmit表单提交
onKeyDown按键按下
onFocus / onBlur获得焦点 / 失去焦点
onMouseEnter鼠标进入元素
条件渲染
// Ternary {isLoggedIn ? : } // Logical AND (short-circuit) {hasError && } // Early return function Page({ user }) { if (!user) return ; return ; }
Hook
useRef
const inputRef = useRef(null); // Access: inputRef.current.focus();

useRef 在渲染间保持值,但不会触发重新渲染

useMemo 与 useCallback
// Memoize expensive computation const sorted = useMemo( () => items.sort(compareFn), [items] ); // Memoize callback const handleClick = useCallback( () => setCount(c => c + 1), [] );
useContext
import { useContext } from "react"; const value = useContext(MyContext);
自定义 Hook
function useLocalStorage(key, initial) { const [value, setValue] = useState(() => { const saved = localStorage.getItem(key); return saved ? JSON.parse(saved) : initial; }); useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue]; } // Usage const [name, setName] = useLocalStorage("name", "");

自定义 Hook 必须以 'use' 开头

Context API
创建与提供
import { createContext, useContext } from "react"; const ThemeCtx = createContext("light"); function App() { return ( ); }
消费
function Page() { const theme = useContext(ThemeCtx); // "dark" return
...
; }