雖然個(gè)人自己編寫了一套路由方式,但因?yàn)橹皇呛唵蔚闹匦落秩玖隧撁娑翰瘢荒軌驅(qū)崿F(xiàn)“后退”“刷新”功能迁酸。所以自己研究了react-router在真實(shí)項(xiàng)目中的應(yīng)用。一個(gè)簡單的側(cè)邊欄+內(nèi)容框。
首先你要?jiǎng)?chuàng)建一個(gè)純凈的react項(xiàng)目谷扣,此處不多講土全。
1、安裝react-router
yarn add react-router-dom
或
npm install react-router-dom
2会涎、修改添加文件目錄
-src/
-Layout/ 存放側(cè)邊欄裹匙,標(biāo)題欄等頁面組件。
-page/ 存放頁面
3末秃、添加路由
修改router.js文件
import React,{Component} from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './home/home';
import Article from './article/article';
import Songs from './article/songs';
import Technology from './article/technology';
import UserMess from './userMess/userMess';
export default class Routers extends Component{
render(){
return(
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/article' component={Article}/>
<Route exact path='/article/songs' component={Songs}/>
<Route exact path='/article/technology' component={Technology}/>
<Route exact path='/userMess' component={UserMess}/>
</Switch>
)
}
}
<Switch>標(biāo)簽概页,表明在這幾個(gè)路由總,只會(huì)有一個(gè)匹配成功的路由返回练慕。
為了更加明了惰匙,我們改一下代碼:
… …
{/* /:id 是一種動(dòng)態(tài)傳入路徑的方法技掏,比如點(diǎn)擊<Link to="/article">article</Link>,此時(shí)/:id == /:article */}
<Route exact path='/:id' component={UserMess}/>
… …
這時(shí)候我們點(diǎn)擊<Link to="/article">article</Link>项鬼,頁面還是只會(huì)返回第一個(gè)匹配成功的Article頁面
但如果我們將Switch換成普通的div哑梳,
再點(diǎn)擊Articles:
可以看到,它加載了所有匹配成功的頁面绘盟。所以根據(jù)需求使用Switch即可鸠真。
4、添加路由控制器
在router.js中配置了所有需要的頁面后龄毡,我們需要側(cè)邊欄能夠控制它的跳轉(zhuǎn)吠卷,所以我們更改sider.js的代碼
import React,{Component} from 'react';
import {
Link
} from 'react-router-dom';
export default class Sider extends Component{
componentDidMount(){
console.log(Link)
}
render(){
return (
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/home">Homes</Link></li>
<li><Link to="/article">Article</Link></li>
<li><Link to="/article/songs">Songs</Link></li>
<li><Link to="/article/technology">Technology</Link></li>
<li><Link to="/userMess">UserMess</Link></li>
<li></li>
</ul>
</div>
)
}
}
通過Link標(biāo)簽,來控制Route的頁面沦零。
這里要注意一下祭隔,Link標(biāo)簽中'to'指向的路徑應(yīng)該與Route中的'path'一一對應(yīng)。
這樣一個(gè)簡單的路由變配置完成了蠢终。
這只是最基礎(chǔ)的第一步序攘。