【React】路由的基础使用
react-router-dom@6的基础使用
1、安装依赖
npm i react-router-dom
默认安装最新版本的
2、在src/router/index.js
import { createBrowserRouter } from "react-router-dom"
/*
createBrowserRouter:[/home]--h5路由
createHashRouter:[/#/home]--哈希路由
*/
const router=createBrowserRouter([
{
path:"/login",
element:<div>登录页</div>
},
{
path:"/",
element:<div>首页</div>
},
{
path:"/mine",
element:<div>我的</div>
},
{
path:"*",
element:<div>404</div>
}
])
// element里可以替换成自己写的组件
export default router
3、在src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider } from "react-router-dom"
import router from "./router/index.js"
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<RouterProvider router={router} />
);