组件复用
性能优化
复杂状态管理
路由与动态加载
异步与数据请求
测试与调试
实战案例
练习与拓展
高阶组件(HOC)
// 高阶组件:接收一个组件,返回一个新组件 function withLogger(Wrapped) { return function(props) { // 副作用:每次渲染打印props React.useEffect(() => { console.log('渲染', props); }); return <Wrapped {...props} />; // 传递所有props }; } // 普通组件 const Hello = props => <h1>{props.msg}</h1>; // 包装后获得增强功能 const LogHello = withLogger(Hello);
Render Props
// Render Props:通过函数作为子组件传递数据 function Mouse({ children }) { const [pos, setPos] = React.useState({x:0,y:0}); // 鼠标移动时更新坐标 return <div onMouseMove={e => setPos({x:e.clientX,y:e.clientY})}> {children(pos)} // 通过children渲染内容 </div>; } // 使用方式: <Mouse>{pos => <span>{pos.x},{pos.y}</span>}</Mouse>
自定义Hook
// 自定义Hook:封装可复用逻辑 function useCounter(init=0) { const [n, setN] = React.useState(init); const inc = () => setN(n+1); // 增加计数 return [n, inc]; } function Demo() { const [n, inc] = useCounter(); return <button onClick={inc}>{n}</button>; }