react-router-dom 会自动安装 react-router核心框架,不需要安装 react-router
react-router-dom v5文档 https://v5.reactrouter.com/web/guides/quick-start

  1. yarn add react-router-dom

image.png

react-router-dom 常用组件

  • 渲染出 标签
  • 利用 H5的 history实现路由
    • 路由导航与原生浏览器操作一致
  • 利用 window.location.hash实现路由切换
    • 通过 url识别路径
  • 只匹配一个路由
  1. import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
  2. function App() {
  3. return (
  4. <Router>
  5. <Switch>
  6. <Route exact path="/" component={Home} />
  7. <Route path="/signin" render={() => <h1>登录页面</h1>} />
  8. <Route path="/signup" component={Signup} />
  9. <Route path="/register" component={Register} />
  10. <Route path="/detail/:id" component={Detail} />
  11. <Route render={ () => <h1>404 Not Found</h1> } />
  12. </Switch>
  13. </Router>
  14. );
  15. }
  16. export default App;

basename

basename 的正确格式是前面有一个前导斜杠,但不能有尾部斜杠
<BrowserRouter basename="/calendar">
basename文档 https://v5.reactrouter.com/web/api/HashRouter/basename-string

  1. <BrowserRouter basename={pkg.name}>
  2. <Router>
  3. {
  4. routes.map(route => {
  5. const {element: Component, ...rest} = route;
  6. return <Route {...rest} element={<Component/>}/>
  7. })
  8. }
  9. </Router>
  10. </BrowserRouter>

最终将被呈现为 <a href="/calendar/today" />