react如何写h5
React 开发 H5 页面的关键步骤
环境搭建与项目初始化
使用 create-react-app 或 Vite 快速初始化项目:
npx create-react-app h5-project --template typescript
# 或
npm create vite@latest h5-project --template react-ts
响应式布局与适配
引入 postcss-px-to-viewport 或 lib-flexible 实现移动端适配:
// postcss.config.js 示例配置
module.exports = {
plugins: {
'postcss-px-to-viewport': {
viewportWidth: 375, // 设计稿宽度
unitPrecision: 5
}
}
}
路由管理
使用 react-router-dom 实现页面跳转:

import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/detail" element={<DetailPage />} />
</Routes>
</BrowserRouter>
);
}
状态管理
简单场景用 useContext,复杂场景用 Redux 或 MobX:
// 创建Context
const UserContext = createContext();
function App() {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={{ user, setUser }}>
<ChildComponent />
</UserContext.Provider>
);
}
组件开发规范
采用原子化设计思想(Atomic Design):

- Atoms(按钮/输入框)
- Molecules(搜索栏)
- Organisms(导航栏)
- Templates(页面骨架)
性能优化
- 使用
React.memo避免不必要的渲染 - 路由懒加载:
const DetailPage = lazy(() => import('./DetailPage')); <Suspense fallback={<Loading />}> <DetailPage /> </Suspense>
调试与真机测试
- Chrome 开发者工具模拟移动端
- 使用
ngrok实现内网穿透真机测试:ngrok http 3000
构建部署
- 生产环境构建:
npm run build - 部署到 CDN 或静态托管服务(如 Vercel/Netlify)
常用 H5 开发库推荐
- UI 框架:Ant Design Mobile、Vant React
- 动画库:Framer Motion、React Spring
- 工具库:ahooks(React Hooks 库)
- 埋点监控:Sentry 或自建监控系统
注意事项
- 禁用
300ms点击延迟:<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> - 处理 iOS 兼容性问题(如
position: fixed) - 使用
rem或vw/vh单位替代px - 优先使用 CSS3 动画替代 JavaScript 动画






