官方文档:https://reactrouter.com/web/guides/quick-start
安装
安装react-router
yarn add react-router-dom
安装@types/react-router-dom
yarn add --dev @types/react-router-dom
使用示例
import React from 'react';import {BrowserRouter as Router,Switch,Route,Link,Redirect} from "react-router-dom";export default function App() {return (<Router><div><nav><ul><li><Link to="/tags">标签</Link></li><li><Link to="/money">记账</Link></li><li><Link to="/statistics">统计</Link></li></ul></nav><Switch><Route path="/tags"><Tags /></Route><Route path="/money"><Money /></Route><Route path="/statistics"><Statistics /></Route><Route exact path="/"><Redirect to="/money" /></Route><Route path="*"><NotFound /></Route></Switch></div></Router>);}function NotFound(){return <h2>你访问的页面不存在</h2>}function Statistics() {return <h2>统计页</h2>;}function Tags() {return <h2>标签页</h2>;}function Money() {return <h2>记账页</h2>;}
注意重定向的写法
添加exact则不模糊匹配
<Route exact path="/"><Redirect to="/money" /></Route>
还可以写成
<Redirect exact from="/" to="/money" />
其他路径跳转404页面
<Route path="*"><NotFound /></Route>
history v.s. hash
Router有2种模式: History 和Hash
如果没有后台服务器,则只能用Hash,hash模式的url都带#号
如果有后台服务器,需要后端配置所有路径都重定向到首页才能用History


修改Hash模式:将BrowserRouter改为HashRouter
import {// BrowserRouter as Router,HashRouter as Router,Switch,Route,Link,Redirect} from "react-router-dom";
index.scss
新建index.scss文件,在里面添加reset
@import-normalize;* {margin:0;padding:0;}* {box-sizing: border-box;}*::after, *::before {box-sizing: border-box;}ul, ol {list-style: none;}a {text-decoration: none; color: inherit;}
在index.tsx中引入
import './index.scss';
styled-component
修改导航栏布局和基本样式
import styled from 'styled-components';const Wrapper = styled.div`height: 100vh;display: flex;flex-direction: column;`const Main = styled.div`flex-grow: 1;overflow: auto;`const Nav = styled.nav`> ul {display: flex;> li {width: 33.3333%;text-align: center;padding: 16px;}}`function App() {return (<Router><Wrapper><Main><Switch><Route path="/tags"><Tags /></Route>// ...</Switch></Main><Nav><ul><li><Link to="/tags">标签</Link></li>// ...</ul></Nav></Wrapper></Router>);}
中文字体
搜索: 中文字体 css github
网页一般用黑体,在helper.scss中声明字体变量$font-hei, 给body添加font-family为$font-hei
将Nav组件移动到components目录
import styled from 'styled-components';import {Link} from 'react-router-dom';import React from 'react';const NavWrapper = styled.nav`line-height: 24px;box-shadow: 0 0 3px rgba(0,0,0,0.2);> ul {display: flex;> li {width: 33.3333%;text-align: center;padding: 16px;}}`const Nav = () => {return (<NavWrapper><ul><li><Link to="/tags">标签</Link></li><li><Link to="/money">记账</Link></li><li><Link to="/statistics">统计</Link></li></ul></NavWrapper>)}export default Nav;
