react-router-dom嵌套路由

路由配置css

 

import React from 'react';
import ReactDOM from 'react-dom';
// import App from './view/App';
import './utils/common.scss';
import { Link, Route, BrowserRouter } from 'react-router-dom'
import Home from './view/home/home'
import Detail from './view/detail/detail'
import Person from './view/person/person'
import DetailChild from './view/detail/detailChild/detailChild'
import DetailChildOne from './view/detail/detailChildOne/detailChildOne'
 
const App = (
    <BrowserRouter>
        <ul>
            <li><Link to="/home">首頁</Link></li>
            <li><Link to="/detail">詳情頁</Link></li>
            <li><Link to="/person">我的中心</Link></li>
        </ul>
        <div>
            <Route exact path="/home" component={Home} />
            <Route path="/detail" render={() => 
                <Detail>
                    <Route exact path="/detail" component={DetailChild} />
                    <Route path="/detail/DetailChildOne" component={DetailChildOne} />
                </Detail>
            } />
            <Route exact path="/person" component={Person} />
        </div>
    </BrowserRouter>
)
 
ReactDOM.render(App, document.getElementById('root'));

 

  在入口文件中進行路由的配置其中BrowserRouter是非hash路由的模式url後面不會帶有#,Route是對應每一個路由組件主要有exact、path、component、render這幾個屬性,其中嵌套路由主要用到的屬性是render屬性。將對應嵌套路由寫到render屬性中,最外邊用父路由包裹住。
  注意!!!render的箭頭函數是沒有{}的react

嵌套路由的頁面react-router

 

import React, { Component } from 'react'
import './detail.scss'
import {withRouter,Link} from 'react-router-dom'
 
class Detail extends Component {
    render() {
        return (
            <div>
                Detail頁面
                <Link to="/detail">嵌套路由1</Link>
                <Link to="/detail/DetailChildOne">嵌套路由2</Link>
                {this.props.children}
            </div>
        )
    }
}
export default withRouter(Detail)

 

  在要進行嵌套路由的頁面要在須要嵌套的地方加上{this.props.children}這樣嵌套的路由就會在顯示在這裏了。
  注意export default withRouter(Detail)必定要用withRouter綁定到組件上否則組件上是沒有this.props.children.history這個方法的這樣就不能經過js的方法this.props.children.history(pathname : '/detail')跳轉dom

結果函數

          

相關文章
相關標籤/搜索