React-Router-嵌套路由

嵌套路由(子路由)
路由里面又有路由, 我们就称之为嵌套路由

新建 Discover.js:

import React from 'react';
import {NavLink, Switch, Route} from "react-router-dom";

function Hot() {
    return (
        <div>推荐</div>
    )
}

function TopList() {
    return (
        <div>排行榜</div>
    )
}

function PlayList() {
    return (
        <div>歌单</div>
    )
}

class Discover extends React.PureComponent {
    render() {
        return (
            <div>
                <NavLink exact to={'/discover'} activeStyle={{color: 'red'}}>推荐</NavLink>
                <NavLink exact to={'/discover/toplist'} activeStyle={{color: 'red'}}>排行榜</NavLink>
                <NavLink exact to={'/discover/playlist'} activeStyle={{color: 'red'}}>歌单</NavLink>

                <Switch>
                    <Route exact path={'/discover'} component={Hot}/>
                    <Route exact path={'/discover/toplist'} component={TopList}/>
                    <Route exact path={'/discover/playlist'} component={PlayList}/>
                </Switch>
            </div>
        )
    }
}

export default Discover;

  

App.js

import React from 'react';
import Home from './components/Home'
import About from './components/About'
import Other from './components/Other'
import User from './components/User'
import Login from './components/Login'
import Discover from './components/Discover'
import {BrowserRouter, NavLink, Route, Switch} from 'react-router-dom';

class App extends React.PureComponent {
    render() {
        return (
            <div>
                <BrowserRouter>
                    <NavLink to={'/home'} activeStyle={{color: 'red'}}>Home</NavLink>
                    <NavLink to={'/about'} activeStyle={{color: 'red'}}>About</NavLink>
                    <NavLink to={'/user'} activeStyle={{color: 'red'}}>User</NavLink>
                    <NavLink to={'/discover'} activeStyle={{color: 'red'}}>广场</NavLink>

                    <Switch>
                        <Route exact path={'/home'} component={Home}/>
                        <Route exact path={'/about'} component={About}/>
                        <Route exact path={'/user'} component={User}/>
                        <Route exact path={'/login'} component={Login}/>
                        <Route path={'/discover'} component={Discover}/>
                        <Route component={Other}/>
                    </Switch>
                </BrowserRouter>
            </div>
        )
    }
}

export default App;

注意点
如果要使用嵌套路由, 那么外层的路由不能添加精准匹配​​exact​​
如果子路由的组件是在 BrowserRouter or HashRouter 中显示的, 那么就不用再当前组件在用使用 BrowserRouter or HashRouter 来包裹 NavLink/Switch/Route

 

posted on 2022-07-13 15:19  ranyonsue  阅读(225)  评论(0编辑  收藏  举报

导航