ReactRouter
安装
sh
npm i react-router-dom
使用配置
src/index.js
jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
const router = createBrowserRouter([
{
path: '/test',
element: <div>/test</div>
},
{
path: '/main',
element: <div>/main</div>
}
])
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<RouterProvider router={router}/>
);
模块化封装
- 页面使用 src/pages
- 路由配置 src/router/index.js
路由跳转
声明式导航:使用 <Link to="/xxx"></Link>
标签
jsx
const Home = () => {
return (
<div>
我是主页
<Link to="/login">跳转到登录页</Link>
</div>
)
}
编程式导航:使用 useNavigate()
钩子函数
js
import { Link, useNavigate } from 'react-router-dom'
const Login = () => {
const navigate = useNavigate()
return (
<div>
<button onClick={() => navigate("/home")}>主页</button>
我是登录页
</div>
)
}
路由传参
查询参数
传递参数:
js
const Home = () => {
const navigate = useNavigate()
return (
<div>
<button onClick={() => navigate("/login?uname=wmh")}>登录</button>
我是主页
</div>
)
}
接收参数:
js
const Login = () => {
const [params] = useSearchParams()
const uname = params.get("uname")
return (
<div>
{uname},您好!
</div>
)
}
路径参数/路由传参
配置路径参数:
js
const router = createBrowserRouter([
{
path: '/login/:uname',
element: <Login/>
},
{
path: '/home',
element: <Home/>
}
])
传递参数:
js
const Home = () => {
const navigate = useNavigate()
return (
<div>
<button onClick={() => navigate("/login/wmh")}>登录</button>
我是主页
</div>
)
}
接收参数:
js
const Login = () => {
const params = useParams()
const uname = params.uname
return (
<div>
{uname},您好!
</div>
)
}
二级路由
- 使用 children 属性配置路由嵌套关系
- 使用
<Outlet />
组件配置二级路由渲染位置
src/router/index.js
js
const router = createBrowserRouter([
{
path: '/',
element: <Layout/>,
children: [
{
path: '/home',
element: <Home/>
},
{
path: '/login/:uname',
element: <Login/>
}
]
}
])
src/pages/Layout/index.jsx
js
const Layout = () => {
return (
<div>
<h1>我是 Layout !!!</h1>
<Outlet/>
</div>
)
}
默认二级路由
js
const router = createBrowserRouter([
{
path: '/',
element: <Layout/>,
children: [
{
// 默认二级路由
index: true,
// path: '/home',
element: <Home/>
},
{
path: '/login/:uname',
element: <Login/>
}
]
}
])
404 路由
js
const router = createBrowserRouter([
// ...
{
path: '*',
element: <NotFound/>,
}
])
路由模式
- history:
createBrowserRouter
- hash:
createHashRouter
@别名路径
别名路径:把 @/
解析成 src/
1、安装 craco 插件
shell
npm i -D @craco/craco
2、项目根目录添加 craco.config.js
js
const path = require('path')
module.exports = {
webpack: {
alias: {
'@': path.resolve(__dirname, './src')
}
}
}
3、修改启动命令
json
{
// ...
"scripts": {
"start": "craco start",
"build": "craco build",
}
// ...
}