React---路由的使用(二)

一、NavLink

  NavLink可以實現路由鏈接的高亮,通過activeClassName指定樣式名
<NavLink activeClassName="demo" className="list-group-item" to="/about">About</NavLink>
<NavLink activeClassName="demo" className="list-group-item" to="/home">Home</NavLink>

二、Switch的使用

                1.通常情況下,path和component是一一對應的關係。
                2.Switch可以提高路由匹配效率(單一匹配)。
1 {/* 註冊路由 */}
2 <Switch>
3         <Route path="/about" component={About}/>
4         <Route path="/home" component={Home}/>
5         <Route path="/home" component={Test}/>
6 </Switch>

三、解決多級路徑刷新頁面樣式丟失的問題

                1.public/index.html 中 引入樣式時不寫 ./ 寫 / (常用)
                2.public/index.html 中 引入樣式時不寫 ./ 寫 %PUBLIC_URL% (常用)
                3.使用HashRouter

四、路由的嚴格匹配與模糊匹配

                1.默認使用的是模糊匹配(簡單記:【輸入的路徑】必須包含要【匹配的路徑】,且順序要一致)
                2.開啓嚴格匹配:<Route exact={true} path="/about" component={About}/>
                3.嚴格匹配不要隨便開啓,需要再開,有些時候開啓會導致無法繼續匹配二級路由
1 <Switch>
2         <Route exact path="/about" component={About}/>
3         <Route exact path="/home" component={Home}/>
4 </Switch>

五、Redirect的使用    

                1.一般寫在所有路由註冊的最下方,當所有路由都無法匹配時,跳轉到Redirect指定的路由
                2.具體編碼:
                        
1 <Switch>
2         <Route path="/about" component={About}/>
3         <Route path="/home" component={Home}/>
4         <Redirect to="/about"/>
5 </Switch>

六、嵌套路由

      1.註冊子路由時要寫上父路由的path值
                 2.路由的匹配是按照註冊路由的順序進行的
      3.代碼:
 1 import React, { Component } from 'react'
 2 import MyNavLink from '../../components/MyNavLink'
 3 import {Route,Switch,Redirect} from 'react-router-dom'
 4 import News from './News'
 5 import Message from './Message'
 6 
 7 export default class Home extends Component {
 8     render() {
 9         return (
10                 <div>
11                     <h3>我是Home的內容</h3>
12                     <div>
13                         <ul className="nav nav-tabs">
14                             <li>
15                                 <MyNavLink to="/home/news">News</MyNavLink>
16                             </li>
17                             <li>
18                                 <MyNavLink to="/home/message">Message</MyNavLink>
19                             </li>
20                         </ul>
21                         {/* 註冊路由 */}
22                         <Switch>
23                             <Route path="/home/news" component={News}/>
24                             <Route path="/home/message" component={Message}/>
25                             <Redirect to="/home/news"/>
26                         </Switch>
27                     </div>
28                 </div>
29             )
30     }
31 }

 

 

 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章