做一个简单的笔记
有两种方式可以实现
- 使用标签
BrowserRouter
来实现 - 使用API
createBrowserRouter
来实现
注意:createBrowserRouter是6.4版本才引入的
这是官方文档
注意,这两个是不兼容的
使用标签 BrowserRouter
来实现
创建路由
// src/router/index.tsx
const router = [
{
path: "/",
element: <div>Home</div>,
},
{
path: "/about",
element: <div>About</div>,
},
];
export default router;
在APP组件中引用
// src/App.tsx
import "./assets/App.css";
import { Button, Divider, Flex } from "antd";
import { Link, useRoutes } from "react-router-dom";
import router from "~/router";
const App = () => {
// 使用useRoutes来使用这个路由
const route = useRoutes(router);
return (
<>
<Flex gap="small" align="flex-start" vertical={false}>
<Button type="primary">
<Link to="/">首页</Link>
</Button>
<Button type="primary">
<Link to="/about">关于</Link>
</Button>
</Flex>
<Divider orientation="left">正文</Divider>
<div>{route}</div>
</>
);
};
export default App;
需要什么路由,就在这个组件中导入什么路由,然后,就可以切换了,实现嵌套路由
在入口处使用BrowserRouter标签
import * as React from "react";
import * as ReactDOM from "react-dom/client";
import "~/assets/index.css";
import { BrowserRouter } from "react-router-dom";
import App from "~/App.tsx";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
);
使用API createBrowserRouter
来实现
在6.4版本引入了 API createBrowserRouter
这个用起来更加优雅
新建路由
// src/router/index.tsx
import { createBrowserRouter } from "react-router-dom";
import App from "~/App.tsx";
const router = createBrowserRouter([
{
path: "/",
element: <App />,
// 用嵌套路由的形式
children: [
{
// 设置index,表示这个是默认渲染的子路由
index: true,
element: <div>Home</div>,
},
{
path: "about",
element: <div>About</div>,
},
],
},
]);
export default router;
修改下入口代码
// src/main.tsx
import * as React from "react";
import * as ReactDOM from "react-dom/client";
import "~/assets/index.css";
import { RouterProvider } from "react-router-dom";
import router from "~/router";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);
APP组件不再放在这个位置,这个位置直接注入新建的路由器就好了
在APP组件中使用 Outlet
标签
Outlet
标签就是用来渲染路由器中对应的子路由的位置
import "./assets/App.css";
import { Button, Divider, Flex } from "antd";
import { Link, Outlet } from "react-router-dom";
const App = () => {
return (
<>
<Flex gap="small" align="flex-start" vertical={false}>
<Button type="primary">
<Link to="">首页</Link>
</Button>
<Button type="primary">
<Link to="about">关于</Link>
</Button>
</Flex>
<Divider orientation="left">正文</Divider>
<Outlet />
</>
);
};
export default App;
标签:dom,App,react,v6,import,router,路由
From: https://www.cnblogs.com/guangdelw/p/18087512