react crash course 2024(7) react router dom

安装

复制代码
npm i react-router-dom

引入

复制代码
import {Route,createBrowserRouter,createRoutesFromElements,RouterProvider} from 'react-router-dom'

在app.jsx

复制代码
const router = createBrowserRouter(
  createRoutesFromElements(<Route index element = {<h1>My App</h1>}/>)
)

const App = () => {
  return <RouterProvider router={router}/>
}

使用object写路由

复制代码
const router = createBrowserRouter([
  {
    path:"/",
    element:(
      <h2>hello rainbow</h2>
    )
  },{
    path:"about",
    element:<h2>little puppy</h2>
  }
])

或直接使用<Route/>组件写路由

复制代码
const router = createBrowserRouter(
  createRoutesFromElements(
  <Route path='/' element={<h2>hello rainbow</h2>}></Route>
))

路由嵌套

复制代码
const router = createBrowserRouter(
  createRoutesFromElements(
  <Route path='/' element={<MainLayout/>}>
    <Route   path="contact" element = {<h5 >some peopel just bad</h5>}/>
  </Route>
))

别忘了放子路由出口

在父 route 元素中使用outlet来渲染其子 route 元素。这允许在渲染子路由时显示嵌套 UI。

相关推荐
Mintopia4 分钟前
一个月速成 AI 工程师:从代码小白到智能工匠的修炼手册
前端·javascript·aigc
Mintopia7 分钟前
Next.js 全栈:接收和处理请求
前端·javascript·next.js
袁煦丞40 分钟前
2025.8.18实验室【代码跑酷指南】Jupyter Notebook程序员的魔法本:cpolar内网穿透实验室第622个成功挑战
前端·程序员·远程工作
Joker Zxc1 小时前
【前端基础】flex布局中使用`justify-content`后,最后一行的布局问题
前端·css
无奈何杨1 小时前
风控系统事件分析中心,关联关系、排行、时间分布
前端·后端
Moment1 小时前
nginx 如何配置防止慢速攻击 🤔🤔🤔
前端·后端·nginx
晓得迷路了1 小时前
栗子前端技术周刊第 94 期 - React Native 0.81、jQuery 4.0.0 RC1、Bun v1.2.20...
前端·javascript·react.js
前端小巷子1 小时前
Vue 自定义指令
前端·vue.js·面试
玲小珑1 小时前
Next.js 教程系列(二十七)React Server Components (RSC) 与未来趋势
前端·next.js