Skip to content

路由配置( 推荐)

基本知识笔记:StudyNote/react-router6.md

安装组件

npm install react-router
或者
yarn add react-router

app.tsx 在该文件中给 App 使用 Router

tsx
import { Button } from "./components/ui/button";
import { Router } from "./router";

export const App = () => {
  return (
    <div>
      <Router />
    </div>
  );
};

router/index.tsx 根据定义编写routes 数组RouterViews 组件

tsx
import { createBrowserRouter, RouterProvider, type RouteObject } from "react-router";

// 简单建了两个简单的组件,稍后给出
import { Home } from "@/pages/home";
import { My } from "@/pages/my";

export const routes: RouteObject[] = [
  {
    path: "/",
    element: <Home />,
    children: [
      {
        path: "my",
        element: <My />,
        index: true, // 当给属性index设置为true时,该组件为父组件的首页
      },
    ],
  },
];


export const Router = () => {
  return <RouterProvider router={createBrowserRouter(routes)} />;
};

pages/home/index.tsx 每个有 children 的父组件都要记得放置 <Outlet />

tsx
import { Outlet } from "react-router-dom";

export const Home = () => {
  return (
    <>
      <div>Home</div>
      {/* 该Home的孩子会在Outlet中显示 没有设置则不会显示My */}
      <Outlet />
    </>
  );
};

pages/my/index.tsx

tsx
export const My = () => {
  return <div>My</div>;
};

显示如下,可以看到 My 显示在 Home 的下面:

image.png

基于 MIT 许可发布