12.React-router-dom6.30的路由表路由设置

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

 yarn add react-router-dom

2.引入

import { NavLink, useRoutes} from '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>
  )
}

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