其他分享
首页 > 其他分享> > React 中router v6 与 v5 中嵌套路由的区别

React 中router v6 与 v5 中嵌套路由的区别

作者:互联网

 

v5中的嵌套路由:

主页面v5中使用{this.props.children}来接收子页面

import React, { Component } from 'react';
export default class About extends Component {
  render() {
    return (<h1>
      欢迎,这里是About
      {this.props.children}    
    </h1>)
  }
}

v5中的路由写法如下:

//引入react jsx写法的必须
import React from 'react'; 
//引入需要用到的页面组件 
import Home from '../pages/home';
import About from '../pages/about';
import Other from '../pages/other';
//引入一些模块
import { BrowserRouter as Router, Route, Routes} from "react-router-dom";

function router(){
return (
<Routes>
    <Route path="/home" component={<Home/>} />
    <Route path="/about" component={<About/>} />
    <Route path='/about' render={()=>{
      <About>
        <Router path='/about/other' component={Other}></Router>
      </About>
    }}>
    </Route>
</Routes>);
}

export default router;

 

v6中的嵌套路由:

主页面中使用<Outlet />来接收子页面

//about.js
import React, { Component } from 'react';
import {Outlet} from "react-router-dom";

export default class About extends Component {
  render() {
    return (<h1>
      欢迎,这里是About
      <Outlet />
    </h1>)
  }
}

v6中路由的写法如下:

//引入react jsx写法的必须
import React from 'react'; 
//引入需要用到的页面组件 
import Home from '../pages/home';
import About from '../pages/about';
import Other from '../pages/other';
//引入一些模块
import { BrowserRouter as Router, Route, Routes} from "react-router-dom";

function router(){
return (
<Routes>
    <Route path="/home" element={<Home/>} />
    <Route path="/about" element={<About/>}>
      <Route path='other' element={<Other/>}></Route>
    </Route>
</Routes>);
}

export default router;

 

两者相比之下,v6的写法更加简洁了。

 

标签:react,About,..,React,v5,v6,router,import,pages
来源: https://www.cnblogs.com/zyfenblog/p/16673620.html