React Router
    安装

    1. yarn add react-router-dom

    安装 TS 声明文件

    1. yarn add --dev @types/react-router-dom

    开始使用

    1. import React from "react";
    2. import {
    3. BrowserRouter as Router,
    4. Switch,
    5. Route,
    6. Link
    7. } from "react-router-dom";
    8. export default function App() {
    9. return (
    10. <Router>
    11. <div>
    12. <nav>
    13. <ul>
    14. <li>
    15. <Link to="/">Home</Link>
    16. </li>
    17. <li>
    18. <Link to="/about">About</Link>
    19. </li>
    20. <li>
    21. <Link to="/users">Users</Link>
    22. </li>
    23. </ul>
    24. </nav>
    25. {/* A <Switch> looks through its children <Route>s and
    26. renders the first one that matches the current URL. */}
    27. <Switch>
    28. <Route path="/about">
    29. <About />
    30. </Route>
    31. <Route path="/users">
    32. <Users />
    33. </Route>
    34. <Route path="/">
    35. <Home />
    36. </Route>
    37. </Switch>
    38. </div>
    39. </Router>
    40. );
    41. }
    42. function Home() {
    43. return <h2>Home</h2>;
    44. }
    45. function About() {
    46. return <h2>About</h2>;
    47. }
    48. function Users() {
    49. return <h2>Users</h2>;
    50. }

    页面渲染在
    React Router 有两种模式:

    • History:有后台服务器需配置所有路径到首页才能用
    • Hash:没用后台服务器只能用 Hash