react-router-dom v6新建layout并且实现路由嵌套

1:在根目录下新建Router.js文件

import Layout from './views/layout'
import { Component } from 'react'
import { Route, BrowserRouter, Routes } from 'react-router-dom'
class Router extends Component {
  render() {
    return (
      <BrowserRouter>
        <Routes>
            <Route path="/*" element={<Layout/>} ></Route>
        </Routes>
      </BrowserRouter>
    )
  }
}
export default Router

备注:要嵌套的路由这里一定要写/* 为了告诉这个路由后续会跟着其它路径

2:index.js修改

import React from 'react';
import ReactDOM from 'react-dom/client';
import Router from './Router'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Router/>
  </React.StrictMode>
);

3:根目录/views/loyout文件夹新建index.js

import Header from '../../common/header'
import Home from '../home'
import Login from '../login'
import { Route, Routes } from 'react-router-dom'
const Layout = () => {
  return (
    <div>
        // header组件根据需要自己创建
        <Header></Header>
        <Routes>
          <Route path="/home" element={<Home/>} />
          <Route path="/login" element={<Login/>} />
        </Routes>
    </div>            
  )
}
export default Layout;

4:根目录/views创建home和login文件夹,各新建一个index.js

import { Component } from 'react'
import { Link } from 'react-router-dom'
class Home extends Component {
  render() {
    return (
        <div>
          <p><Link to="/login">登录</Link></p>
          <p><Link to="/home">首页</Link></p>
          this is Home page
        </div>            
    )
  }
}
export default Home;

5:实现效果

相关推荐