react-router使用教程
0. 關于url中#的作用:
- 學習: http://www.ruanyifeng.com/blog/2011/03/url_hash.html
- '#'代表網頁中的一個位置。其右面的字符,就是該位置的標識符
- 改變#不觸發(fā)網頁重載
- 改變#會改變?yōu)g覽器的訪問歷史
- window.location.hash讀取#值
- window.onhashchange = func 監(jiān)聽hash改變
1. reat-router
- github主頁: https://github.com/ReactTraining/react-router
- 官網教程: https://github.com/reactjs/react-router-tutorial/(官方教程)
- 一峰教程: http://www.ruanyifeng.com/blog/2016/05/react_router.html?utm_source=tool.lu
2. react-router庫中的相關組件
- 包含的相關組件:
- Router: 路由器組件, 用來包含各個路由組件
- Route: 路由組件, 注冊路由
- IndexRoute: 默認路由組件
- hashHistory: 路由的切換由URL的hash變化決定,即URL的#部分發(fā)生變化
- Link: 路由鏈接組件
- Router: 路由器組件
- 屬性: history={hashHistory} 用來監(jiān)聽瀏覽器地址欄的變化, 并將URL解析成一個地址對象,供React Router匹配
- 子組件: Route
- Route: 路由組件
- 屬性1: path="/xxx"
- 屬性2: component={Xxx}
- 根路由組件: path="/"的組件, 一般為App
- 子路由組件: 子<Route>配置的組件
- IndexRoute: 默認路由
- 當父路由被請求時, 默認就會請求此路由組件
- hashHistory
- 用于Router組件的history屬性
- 作用: 為地址url生成?_k=hash, 用于內部保存對應的state
- Link: 路由鏈接
- 屬性1: to="/xxx"
- 屬性2: activeClassName="active"
3. 配置(從官方教程樣例中拷貝)
* webpack配置: webpack.config.js
```
module.exports = {
//入口js
entry: './index.js',
//編譯打包輸出
output: {
filename: 'bundle.js',
publicPath: ''
},
module: {
//使用的loaders
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react'}
]
}
}
```
* 包配置: package.json
```
{
"name": "tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --inline --content-base ."
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.0"
},
"devDependencies": {
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"http-server": "^0.8.5",
"webpack": "^1.12.13",
"webpack-dev-server": "^1.14.1"
}
}
```
4. 編碼
* 定義各個路由組件
* About.js
```
import React from 'react'
function About() {
return <div>About組件內容</div>
}
export default About
```
* Home.js
```
import React from 'react'
function Home() {
return <div>Home組件內容2</div>
}
export default Home
```
* Repos.js
```
import React, {Component} from 'react'
export default class Repos extends Component {
render() {
return (
<div>Repos組件</div>
)
}
}
```
* 定義應用組件: App.js
```
import React, {Component} from 'react'
import {Link} from 'react-router'
export default class App extends Component {
render() {
return (
<div>
<h2>Hello, React Router!</h2>
<ul>
<li><Link to="/about" activeClassName="active">About2</Link></li>
<li><Link to="/repos" activeClassName="active">Repos2</Link></li>
</ul>
{this.props.children}
</div>
)
}
}
```
* 定義入口JS: index.js-->渲染組件
```
import React from 'react'
import {render} from 'react-dom'
import {Router, Route, IndexRoute, hashHistory} from 'react-router'
import App from './modules/App'
import About from './modules/About'
import Repos from './modules/Repos'
import Home from './modules/Home'
render((
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/about" component={About}></Route>
<Route path="/repos" component={Repos}></Route>
</Route>
</Router>
), document.getElementById('app'))
```
* 主頁面: index.html
```
<style>
.active {
color: red;
}
</style>
<div id=app></div>
<script src="bundle.js"></script>
```
5. 傳遞請求參數(shù)
* repo.js: repos組件下的分路由組件
```
import React from 'react'
export default function ({params}) {
let {username, repoName} = params
return (
<div>用戶名:{username}, 倉庫名:{repoName}</div>
)
}
```
* repos.js
```
import React from 'react'
import NavLink from './NavLink'
export default class Repos extends React.Component {
constructor(props) {
super(props);
this.state = {
repos: [
{username: 'faceback', repoName: 'react'},
{username: 'faceback', repoName: 'react-router'},
{username: 'Angular', repoName: 'angular'},
{username: 'Angular', repoName: 'angular-cli'}
]
};
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit () {
const repos = this.state.repos
repos.push({
username: this.refs.username.value,
repoName: this.refs.repoName.value
})
this.setState({repos})
this.refs.username.value = ''
this.refs.repoName.value = ''
}
render() {
return (
<div>
<h2>Repos</h2>
<ul>
{
this.state.repos.map((repo, index) => {
const to = `/repos/${repo.username}/${repo.repoName}`
return (
<li key={index}>
<Link to={to} activeClassName='active'>{repo.repoName}</Link>
</li>
)
})
}
<li>
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="用戶名" ref='username'/> / {' '}
<input type="text" placeholder="倉庫名" ref='repoName'/>{' '}
<button type="submit">添加</button>
</form>
</li>
</ul>
{this.props.children}
</div>
);
}
}
```
* index.js: 配置路由
```
<Route path="/repos" component={Repos}>
<Route path="/repos/:username/:repoName" component={Repo}/>
</Route>
```
6. 優(yōu)化Link組件
* NavLink.js
```
import React from 'react'
import {Link} from 'react-router'
export default function NavLink(props) {
return <Link {...props} activeClassName="active"/>
}
```
* Repos.js
```
<NavLink to={to}>{repo.repoName}</NavLink>
```
7.switch組件
今天在完善一個項目的時候,重新總結了一點switch相關的東西。
<switch>
該組件用來渲染匹配地址的第一個<Route>或者<Redirect>。那么它與使用一堆route又有什么區(qū)別呢?
<Switch>的獨特之處是獨它僅僅渲染一個路由。相反地,每一個包含匹配地址(location)的<Route>都會被渲染。思考下面的代碼:
<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>
如果現(xiàn)在的URL是/about,那么<About>, <User>, 還有<NoMatch>都會被渲染,因為它們都與路徑(path)匹配。這種設計,允許我們以多種方式將多個<Route>組合到我們的應用程序中,例如側欄(sidebars),面包屑(breadcrumbs),bootstrap tabs等等。 然而,偶爾我們只想選擇一個<Route>來渲染。如果我們現(xiàn)在處于/about,我們也不希望匹配/:user(或者顯示我們的 “404” 頁面 )。以下是使用 Switch 的方法來實現(xiàn):
<Switch>
<Route exact path="/" component={Home}/> <Route path="/about" component={About}/> <Route path="/:user" component={User}/> <Route component={NoMatch}/>
</Switch>
現(xiàn)在,如果我們處于/about,<Switch>將開始尋找匹配的<Route>。<Route path="/about"/>將被匹配, <Switch>將停止尋找匹配并渲染<About>。同樣,如果我們處于/michael,<User>將被渲染。