前言
React Router是一个用于处理路由和导航的库,它为React应用程序提供了强大的路由管理能力。而嵌套路由则是React Router中的一个重要概念,它允许您在应用程序中创建更复杂的页面布局和导航结构。
嵌套路由(子路由)
- 路由里面又有路由, 我们就称之为嵌套路由
新建 Discover.js:
代码语言:javascript复制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:
代码语言:javascript复制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
最后
本期结束咱们下次再见