React框架核心概念与实践1. 技术分析1.1 React概述React是Facebook开发的用户界面库React特点 组件化: 复用性强 虚拟DOM: 高效渲染 JSX: JavaScript扩展语法 单向数据流: 数据流向清晰 核心概念: 组件 状态管理 生命周期1.2 React组件组件类型 函数组件: 简洁、推荐 类组件: 功能完整 组件特性: props: 输入属性 state: 内部状态 hooks: 函数组件增强1.3 虚拟DOM概念说明优势虚拟DOMJavaScript对象表示DOM减少真实DOM操作diff算法比较新旧虚拟DOM最小化更新批处理合并多次更新提高性能2. 核心功能实现2.1 函数组件与Hooksimport { useState, useEffect } from react; function Counter() { const [count, setCount] useState(0); const [name, setName] useState(); useEffect(() { document.title Count: ${count}; return () { document.title React App; }; }, [count]); return ( div h1Counter: {count}/h1 button onClick{() setCount(c c 1)} Increment /button input typetext value{name} onChange{(e) setName(e.target.value)} placeholderEnter name / /div ); } function UserProfile({ user }) { const [loading, setLoading] useState(true); const [error, setError] useState(null); useEffect(() { fetch(/api/users/${user.id}) .then(res res.json()) .then(data { setUser(data); setLoading(false); }) .catch(err { setError(err.message); setLoading(false); }); }, [user.id]); if (loading) return divLoading.../div; if (error) return divError: {error}/div; return ( div classNameprofile h2{user.name}/h2 p{user.email}/p /div ); }2.2 状态管理import { useState, useReducer } from react; // 使用useState管理简单状态 function TodoList() { const [todos, setTodos] useState([]); const [input, setInput] useState(); const addTodo () { if (input.trim()) { setTodos(prev [...prev, { id: Date.now(), text: input }]); setInput(); } }; const deleteTodo (id) { setTodos(prev prev.filter(todo todo.id ! id)); }; return ( div input value{input} onChange{(e) setInput(e.target.value)} onKeyPress{(e) e.key Enter addTodo()} / button onClick{addTodo}Add Todo/button ul {todos.map(todo ( li key{todo.id} {todo.text} button onClick{() deleteTodo(todo.id)}×/button /li ))} /ul /div ); } // 使用useReducer管理复杂状态 const initialState { count: 0 }; function reducer(state, action) { switch (action.type) { case increment: return { count: state.count 1 }; case decrement: return { count: state.count - 1 }; case reset: return initialState; default: return state; } } function CounterWithReducer() { const [state, dispatch] useReducer(reducer, initialState); return ( div Count: {state.count} button onClick{() dispatch({ type: increment })}/button button onClick{() dispatch({ type: decrement })}-/button button onClick{() dispatch({ type: reset })}Reset/button /div ); }2.3 Context与高阶组件import { createContext, useContext } from react; // Context创建 const ThemeContext createContext(light); function ThemeProvider({ children }) { const [theme, setTheme] useState(light); const toggleTheme () { setTheme(prev prev light ? dark : light); }; return ( ThemeContext.Provider value{{ theme, toggleTheme }} {children} /ThemeContext.Provider ); } // 使用Context function ThemedButton() { const { theme, toggleTheme } useContext(ThemeContext); return ( button onClick{toggleTheme} style{{ background: theme dark ? #333 : #fff, color: theme dark ? #fff : #333 }} Toggle Theme /button ); } // 高阶组件 function withLoading(Component) { return function WithLoading({ isLoading, ...props }) { if (isLoading) { return divLoading.../div; } return Component {...props} /; }; } const EnhancedComponent withLoading(MyComponent);3. 性能对比3.1 函数组件vs类组件特性函数组件类组件简洁性高低Hooks支持是否状态管理useState/useReducerthis.state性能略优略差3.2 状态管理方案对比方案复杂度适用场景学习曲线useState低简单状态低useReducer中复杂状态中Redux高大型应用高Context中跨组件共享中3.3 渲染优化对比方法效果复杂度memo中低useMemo高中useCallback高中4. 最佳实践4.1 组件设计原则// 单一职责原则 function UserAvatar({ src, alt }) { return img src{src} alt{alt} classNameavatar /; } // 可复用性 function Button({ children, variant primary, onClick }) { const variants { primary: btn-primary, secondary: btn-secondary }; return ( button className{btn ${variants[variant]}} onClick{onClick} {children} /button ); }4.2 Hooks规则// Hooks必须在顶层调用 function MyComponent() { // ✅ 正确在顶层 const [count, setCount] useState(0); if (count 5) { // ❌ 错误在条件中 const [name, setName] useState(); } return div{count}/div; }5. 总结React是构建现代Web应用的强大工具函数组件推荐的组件写法Hooks函数组件的增强功能状态管理多种方案可选性能优化memo、useMemo、useCallback对比数据如下函数组件比类组件更简洁useState适合简单状态useReducer适合复杂状态逻辑Context适合跨组件共享状态
React框架核心概念与实践
React框架核心概念与实践1. 技术分析1.1 React概述React是Facebook开发的用户界面库React特点 组件化: 复用性强 虚拟DOM: 高效渲染 JSX: JavaScript扩展语法 单向数据流: 数据流向清晰 核心概念: 组件 状态管理 生命周期1.2 React组件组件类型 函数组件: 简洁、推荐 类组件: 功能完整 组件特性: props: 输入属性 state: 内部状态 hooks: 函数组件增强1.3 虚拟DOM概念说明优势虚拟DOMJavaScript对象表示DOM减少真实DOM操作diff算法比较新旧虚拟DOM最小化更新批处理合并多次更新提高性能2. 核心功能实现2.1 函数组件与Hooksimport { useState, useEffect } from react; function Counter() { const [count, setCount] useState(0); const [name, setName] useState(); useEffect(() { document.title Count: ${count}; return () { document.title React App; }; }, [count]); return ( div h1Counter: {count}/h1 button onClick{() setCount(c c 1)} Increment /button input typetext value{name} onChange{(e) setName(e.target.value)} placeholderEnter name / /div ); } function UserProfile({ user }) { const [loading, setLoading] useState(true); const [error, setError] useState(null); useEffect(() { fetch(/api/users/${user.id}) .then(res res.json()) .then(data { setUser(data); setLoading(false); }) .catch(err { setError(err.message); setLoading(false); }); }, [user.id]); if (loading) return divLoading.../div; if (error) return divError: {error}/div; return ( div classNameprofile h2{user.name}/h2 p{user.email}/p /div ); }2.2 状态管理import { useState, useReducer } from react; // 使用useState管理简单状态 function TodoList() { const [todos, setTodos] useState([]); const [input, setInput] useState(); const addTodo () { if (input.trim()) { setTodos(prev [...prev, { id: Date.now(), text: input }]); setInput(); } }; const deleteTodo (id) { setTodos(prev prev.filter(todo todo.id ! id)); }; return ( div input value{input} onChange{(e) setInput(e.target.value)} onKeyPress{(e) e.key Enter addTodo()} / button onClick{addTodo}Add Todo/button ul {todos.map(todo ( li key{todo.id} {todo.text} button onClick{() deleteTodo(todo.id)}×/button /li ))} /ul /div ); } // 使用useReducer管理复杂状态 const initialState { count: 0 }; function reducer(state, action) { switch (action.type) { case increment: return { count: state.count 1 }; case decrement: return { count: state.count - 1 }; case reset: return initialState; default: return state; } } function CounterWithReducer() { const [state, dispatch] useReducer(reducer, initialState); return ( div Count: {state.count} button onClick{() dispatch({ type: increment })}/button button onClick{() dispatch({ type: decrement })}-/button button onClick{() dispatch({ type: reset })}Reset/button /div ); }2.3 Context与高阶组件import { createContext, useContext } from react; // Context创建 const ThemeContext createContext(light); function ThemeProvider({ children }) { const [theme, setTheme] useState(light); const toggleTheme () { setTheme(prev prev light ? dark : light); }; return ( ThemeContext.Provider value{{ theme, toggleTheme }} {children} /ThemeContext.Provider ); } // 使用Context function ThemedButton() { const { theme, toggleTheme } useContext(ThemeContext); return ( button onClick{toggleTheme} style{{ background: theme dark ? #333 : #fff, color: theme dark ? #fff : #333 }} Toggle Theme /button ); } // 高阶组件 function withLoading(Component) { return function WithLoading({ isLoading, ...props }) { if (isLoading) { return divLoading.../div; } return Component {...props} /; }; } const EnhancedComponent withLoading(MyComponent);3. 性能对比3.1 函数组件vs类组件特性函数组件类组件简洁性高低Hooks支持是否状态管理useState/useReducerthis.state性能略优略差3.2 状态管理方案对比方案复杂度适用场景学习曲线useState低简单状态低useReducer中复杂状态中Redux高大型应用高Context中跨组件共享中3.3 渲染优化对比方法效果复杂度memo中低useMemo高中useCallback高中4. 最佳实践4.1 组件设计原则// 单一职责原则 function UserAvatar({ src, alt }) { return img src{src} alt{alt} classNameavatar /; } // 可复用性 function Button({ children, variant primary, onClick }) { const variants { primary: btn-primary, secondary: btn-secondary }; return ( button className{btn ${variants[variant]}} onClick{onClick} {children} /button ); }4.2 Hooks规则// Hooks必须在顶层调用 function MyComponent() { // ✅ 正确在顶层 const [count, setCount] useState(0); if (count 5) { // ❌ 错误在条件中 const [name, setName] useState(); } return div{count}/div; }5. 总结React是构建现代Web应用的强大工具函数组件推荐的组件写法Hooks函数组件的增强功能状态管理多种方案可选性能优化memo、useMemo、useCallback对比数据如下函数组件比类组件更简洁useState适合简单状态useReducer适合复杂状态逻辑Context适合跨组件共享状态