index
——以 移动端新闻头条项目为例
# 技术栈
官方脚手架工具:
create-react-appHooks状态管理工具:
reduxUI组件库:
antd异步请求:
axios路由:
react-router样式:
sass、解决样式问题库css Modules类型检查:
TypeScriptlink:
Eslint
# 项目搭建
脚手架创建命令:
npx create-react-app my-app --template typescript调整项目结构
基本项目结构
/src /assets 项目资源文件,比如,图片 等 /components 通用组件 /pages 页面 /store Redux 状态仓库 /types TS 类型,包括:接口、redux等类型 /utils 工具,比如,token、axios 的封装等 App.scss 根组件样式文件 App.tsx 根组件 index.scss 全局样式 index.tsx 项目入口1
2
3
4
5
6
7
8
9
10
11基础样式设置
src/index.tsx 中:
import ReactDOM from 'react-dom' import './index.scss' import App from './App' ReactDOM.render(<App />, document.getElementById('root'))1
2
3
4
5src/index.scss 中:
html, body { margin: 0; padding: 0; } html, body, #root { height: 100%; } p, h2, h3 { margin: 0; }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17src/App.tsx 中:
import './App.scss' function App() { return <div className="app"></div> } export default App1
2
3
4
5
6
7src/App.scss 中:
.app { height: 100%; }1
2
3注:为了统一操作,直接删除 src 下的所有文件后,再调整
# 安装包
# sass样式
脚手架内置了 sass,只需要安装相关包即可
yarn add sass;
1
为了解决样式引入而导致的样式冲突问题
在 react 中这样使用样式文件
import styles from './index.module.scss'
const Home = ()=>{
return <div className={styles.root}></div>
}
1
2
3
4
5
2
3
4
5
# react-router-dom路由
使用 ts 开发,需要对第三方包引入类型声明文件
yarn add react-router-dom@5.3.0
yarn add @types/react-router-dom -D
1
2
2
pages/Login/index.tsx 中:
const Login = () => {
return <div>登录页面</div>
}
export default Login
1
2
3
4
2
3
4
App.tsx 中:
// 导入路由
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
// 导入页面组件
import Login from './pages/Login'
import Layout from './pages/Layout'
// 配置路由规则
function App() {
return (
<Router>
<div className="app">
<Switch>
<Route path="/home" component={Layout} />
<Route path="/login" component={Login} />
</Switch>
</div>
</Router>
)
}
export default App
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
编辑 (opens new window)
上次更新: 2023/02/07, 15:11:55