# 使用CRA创建项目
npm create-react-app react-router-pro
# 安装最新的ReactRouter包
npm i react-router-dom
# 启动项目
npm run start
//index.js
import React from 'react'
import ReactDOM from 'react-dom/client'
const router = createBrowserRouter([
{
path:'/login',
element: <div>登录</div>
},
{
path:'/article',
element: <div>文章</div>
}
])
ReactDOM.createRoot(document.getElementById('root')).render(
<RouterProvider router={router}/>
)
1.router下index.js文件
import Login from '../page/Login'
import Article from '../page/Article'
import { createBrowserRouter, createHashRouter } from 'react-router-dom'
const router = createBrowserRouter([
{
path: '/login',
element: <Login />
},
{
path: '/article/:id/:name',
element: <Article />
}
])
console.log(router)
export default router
2.index.js文件
import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import reportWebVitals from './reportWebVitals'
import { RouterProvider } from 'react-router-dom'
// 1. 导入路由router
import router from './router'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<React.StrictMode>
{/* 2. 路由绑定 */}
<RouterProvider router={router}></RouterProvider>
</React.StrictMode>
)
reportWebVitals()
import { Link, useNavigate } from 'react-router-dom'
const Login = () => {
const navigate = useNavigate()
return (
<div>
我是登录页
{/* 声明式的写法 */}
<Link to="/article">跳转到文章页</Link>
{/* 命令式的写法(编程式导航 */}
<button onClick={() => navigate('/article')}>跳转到文章页</button>
<button onClick={() => navigate('/article?id=1001&name=jack')}>searchParams传参</button>
<button onClick={() => navigate('/article/1001/jack')}>params传参</button>
</div>
)
}
export default Login
import { useParams, useSearchParams } from "react-router-dom"
const Article = () => {
// const [params] = useSearchParams()
// const id = params.get('id')
// const name = params.get('name')
const params = useParams()
const id = params.id
const name = params.name
return <div>我是文章页{id}-{name}</div>
/*
需要在router下的index.js文件
{
path: '/article/:id/:name',
element: <Article />
},
*/
}
export default Article
import Login from '../page/Login'
import Article from '../page/Article'
import Layout from '../page/Layout'
import Board from '../page/Board'
import About from '../page/About'
import NotFound from '../page/NotFound'
import { createBrowserRouter, createHashRouter } from 'react-router-dom'
const router = createBrowserRouter([
{
path: '/',
element: <Layout />,
children: [
// 设置为默认二级路由 一级路由访问的时候,它也能得到渲染
{
index: true,
element: <Board />
},
{
path: 'about',
element: <About />
}
]
},
{
path: '/login',
element: <Login />
},
{
path: '/article/:id/:name',
element: <Article />
},
{
path: '*',
element: <NotFound />
}
])
console.log(router)
export default router
import { Link, Outlet } from "react-router-dom"
const Layout = () => {
return (
<div>
我是一级路由layout组件
<Link to="/">面板</Link>
<Link to="/about">关于</Link>
{/* 配置二级路由的出口 */}
<Outlet />
</div>
)
}
export default Layout