React-router6的路由表+嵌套路由详解

1.下载6版本的react-router-dom

 yarn add react-router-dom

3.创建路由表

//在src目录下建立一个文件夹routes,在该目录下新建一个index.js,随后写下自己需要的路由组件
import { Navigate } from 'react-router-dom'
import Home from '../pages/Home'
import About from '../pages/About'

const indexRouter =  [
  {
    path: '/about',
    //这里是你需要的路由组件
    element: <About />
  },
  {
    path: '/home',
    element: <Home />
  },
    //使用Navigate进行重定向
  {
    path: '/',
    element: <Navigate to='/about' />
  }
]

export default indexRouter

4.在页面下进行引入并展示

import indexRouter from './routes'
//在function定义
const elementRoute = useRoutes(indexRouter)
//在页面引入
<div className="panel-body">
  {elementRoute}
</div>

5.页面代码

import React from 'react'
import { NavLink, useRoutes,} from 'react-router-dom'
import indexRouter from './routes'
import './App.css'

export default function App() {
  function active({isActive}) {
    return  isActive ? 'back' : '' 
  }
  const elementRoute = useRoutes(indexRouter)
  return (
    <div>
      <div className="row">
        <div className="col-xs-offset-2 col-xs-8">
          <div className="page-header"><h2>React Router Demo</h2></div>
        </div>
      </div>
      <div className="row">
        <div className="col-xs-2 col-xs-offset-2">
          <div className="list-group">
            <NavLink to='/about' className={active}>About</NavLink>
            <NavLink to='/home' className={active}>Home</NavLink>
          </div>
        </div>
        <div className="col-xs-6">
          <div className="panel">
            <div className="panel-body">
              {elementRoute}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

6.嵌套路由

1.只要在根组件引用了路由就不用再子组件再次引用了(!!!切记)

2.嵌套路由

import { Navigate } from 'react-router-dom'
import Home from '../pages/Home'
import Message from '../pages/Message'
import News from '../pages/News'

const indexRouter =  [
  {
    path: '/home',
    element: <Home />,
      //加children进行嵌套
    children:[
      {
        path:'news',
        element:<News/>
      },
      {
        path:'message',
        element:<Message/>
      }
    ]
  },
  {
    path: '/',
    element: <Navigate to='/home' />
  }
]

export default indexRouter

2.在home.jsx操作

import React  from 'react'
//Outlet是嵌套路由的占位符
import { NavLink,Navigate, Outlet } from 'react-router-dom'


export default function Home() {
  return (
    <div>
      <h1>我是Home内容</h1>
      <ul>
      //嵌套路由千万不要加/ 
        <NavLink to='news'>News</NavLink>
        <NavLink to='message'>Message</NavLink>
      </ul>
//路由显示的位置就在这里
      <div>
        <Outlet/>
      </div>
    </div>
  )
}

你可能感兴趣的:(react,react.js,javascript,前端)