react-router APIjavascript
安装命令:html
$ npm install -S react-router
使用展现:java
import { Router } from 'react-router'; render(<Router/>, document.getElementById('app'));
Router组件自己只是一个容器,真正的路由要经过Route组件定义。react
import { Router, Route, hashHistory } from 'react-router'; render(( <Router history={hashHistory}> <Route path="/" component={App}/> </Router> ), document.getElementById('app'));
代码解释:git
用户访问根路由/
(好比http://www.example.com/
),组件APP
就会加载到document.getElementById('app')。github
Router
组件有一个参数history
,它的值hashHistory
表示,路由的切换由URL的hash
变化决定,即URL的#部分发生变化。举例来讲,用户访问http://www.example.com/
,实际会看到的是http://www.example.com/#/
。npm
Route
组件定义了URL路径与组件的对应关系。你能够同时使用多个Route组件。浏览器
<Router history={hashHistory}> <Route path="/" component={App}/> <Route path="/repos" component={Repos}/> <Route path="/about" component={About}/> </Router>
上面代码中,用户访问/repos
时,会先加载App
组件,而后在它的内部再加载Repos
组件。服务器
<App> <Repos/> </App>
App组件要写成下面的样子。react-router
export default React.createClass({ render() { return <div> {this.props.children} </div> } })
上面代码中,App组件的this.props.children
属性就是子组件。
子路由也能够不写在Router
组件里面,单独传入Router
组件的routes
属性。
let routes = <Route path="/" component={App}> <Route path="/repos" component={Repos}/> <Route path="/about" component={About}/> </Route>; <Router routes={routes} history={browserHistory}/>
Route
组件的path
属性指定路由的匹配规则。这个属性是能够省略的,这样的话,无论路径是否匹配,老是会加载指定组件。
<Route path="inbox" component={Inbox}> <Route path="messages/:id" component={Message} /> </Route>
上面代码中,当用户访问/inbox/messages/:id
时,会加载下面的组件。
若是省略外层Route
的path
参数,写成下面的样子。
<Route component={Inbox}> <Route path="inbox/messages/:id" component={Message} /> </Route>
<Route path="/hello/:name"> // 匹配 /hello/michael // 匹配 /hello/ryan
<Route path="/hello(/:name)"> // 匹配 /hello // 匹配 /hello/michael // 匹配 /hello/ryan
<Route path="/files/*.*"> // 匹配 /files/hello.jpg // 匹配 /files/hello.html
<Route path="/files/*"> // 匹配 /files/ // 匹配 /files/a // 匹配 /files/a/b
通配符规则:
:paramName
匹配URL的一个部分,直到遇到下一个/、?、#为止。这个路径参数能够经过this.props.params.paramName取出。
()
表示URL的这个部分是可选的。
*
匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。
**
匹配任意字符,直到下一个/、?、#为止。匹配方式是贪婪模式。
上面的代码会发现访问根路径会加载不到子组件。IndexRoute
就是解决这个问题,显式指定Home
是根路由的子组件,即指定默认状况下加载的子组件。你能够把IndexRoute
想象成某个路径的index.html。
<Router> <Route path="/" component={App}> <IndexRoute component={Home}/> <Route path="accounts" component={Accounts}/> <Route path="statements" component={Statements}/> </Route> </Router>
IndexRoute
组件没有路径参数path
。
<Redirect>
组件用于路由的跳转,即用户访问一个路由,会自动跳转到另外一个路由。
<Route path="inbox" component={Inbox}> {/* 从 /inbox/messages/:id 跳转到 /messages/:id */} <Redirect from="messages/:id" to="/messages/:id" /> </Route>
IndexRedirect
组件用于访问根路由的时候,将用户重定向到某个子组件。
<Route path="/" component={App}> <IndexRedirect to="/welcome" /> <Route path="welcome" component={Welcome} /> <Route path="about" component={About} /> </Route>
push(pathOrLoc)
router.push('/users/12') // or with a location descriptor object router.push({ pathname: '/users/12', query: { modal: true }, state: { fromDashboard: true } })
replace(pathOrLoc)
go(n)
goBack()
goForward()
setRouteLeaveHook(route, hook)
Link
组件用于取代<a>
元素,生成一个连接,容许用户点击后跳转到另外一个路由。它基本上就是<a>
元素的React 版本,能够接收Router
的状态。
render() { return <div> <ul role="nav"> <li><Link to="/about">About</Link></li> <li><Link to="/repos">Repos</Link></li> </ul> </div> }
若是但愿当前的路由与其余路由有不一样样式,这时可使用Link
组件的activeStyle
属性
<Link to="/about" activeStyle={{color: 'red'}}>About</Link> <Link to="/repos" activeStyle={{color: 'red'}}>Repos</Link>
另外一种作法是,使用activeClassName
指定当前路由的Class
。
<Link to="/about" activeClassName="active">About</Link> <Link to="/repos" activeClassName="active">Repos</Link>
若是连接到根路由/
,不要使用Link
组件,而要使用IndexLink
组件。
这是由于对于根路由来讲,activeStyle
和activeClassName
会失效,或者说老是生效,由于/
会匹配任何子路由。而IndexLink组件会使用路径的精确匹配。
<IndexLink to="/" activeClassName="active"> Home </IndexLink>
另外一种方法是使用Link
组件的onlyActiveOnIndex
属性,也能达到一样效果。
<Link to="/" activeClassName="active" onlyActiveOnIndex={true}> Home </Link>
实际上,IndexLink
就是对Link
组件的onlyActiveOnIndex
属性的包装。
Router
组件的history
属性,用来监听浏览器地址栏的变化,并将URL解析成一个地址对象,供 React Router 匹配。
hashHistory
若是设为hashHistory
,路由将经过URL的hash部分(#)切换,URL的形式相似example.com/#/some/path。
browserHistory
若是设为browserHistory
,浏览器的路由就再也不经过Hash完成了,而显示正常的路径example.com/some/path,背后调用的是浏览器的History API
种状况须要对服务器改造。不然用户直接向服务器请求某个子路由,会显示网页找不到的404错误。
createMemoryHistory
createMemoryHistory
主要用于服务器渲染。它建立一个内存中的history对象,不与浏览器URL互动。
const history = createMemoryHistory(location)
useRouterHistory(createHistory)
import createHashHistory from 'history/lib/createHashHistory' const history = useRouterHistory(createHashHistory)({ queryKey: false })
Link
组件用于正常的用户点击跳转,可是有时还须要表单跳转、点击按钮跳转等操做。这些状况怎么跟React Router对接呢?
<form onSubmit={this.handleSubmit}> <input type="text" placeholder="userName"/> <input type="text" placeholder="repo"/> <button type="submit">Go</button> </form>
第一种方法是使用browserHistory.push
import { browserHistory } from 'react-router' // ... handleSubmit(event) { event.preventDefault() const userName = event.target.elements[0].value const repo = event.target.elements[1].value const path = `/repos/${userName}/${repo}` browserHistory.push(path) }
第二种方法是使用context
对象。
export default React.createClass({ // ask for `router` from context contextTypes: { router: React.PropTypes.object }, handleSubmit(event) { // ... this.context.router.push(path) }, })
React.render(( <Router> <Route path="/" component={App}> <Route path="about" component={About} /> <Route path="inbox" component={Inbox}> <Route path="messages/:id" component={Message} /> </Route> </Route> </Router> ), document.body)
| URL | 组件|
| ------| ------ |
| / | APP |
| /about | App -> About |
| /inbox | App -> Inbox |
| /inbox/messages/:id | App -> Inbox -> Message |
React.render(( <Router> <Route path="/" component={App}> {/* 当 url 为/时渲染 Dashboard */} <IndexRoute component={Dashboard} /> <Route path="about" component={About} /> <Route path="inbox" component={Inbox}> <Route path="messages/:id" component={Message} /> </Route> </Route> </Router> ), document.body)
URL | 组件 |
---|---|
/ | App -> Dashboard |
/about | App -> About |
/inbox | App -> Inbox |
/inbox/messages/:id | App -> Inbox -> Message |
React.render(( <Router> <Route path="/" component={App}> <IndexRoute component={Dashboard} /> <Route path="about" component={About} /> <Route path="inbox" component={Inbox}> {/* 使用 /messages/:id 替换 messages/:id */} <Route path="/messages/:id" component={Message} /> </Route> </Route> </Router> ), document.body)
URL | 组件 |
---|---|
/ | App -> Dashboard |
/about | App -> About |
/inbox | App -> Inbox |
/messages/:id | App -> Inbox -> Message |
如今任何人访问 /inbox/messages/5 都会看到一个错误页面。
import { Redirect } from 'react-router' React.render(( <Router> <Route path="/" component={App}> <IndexRoute component={Dashboard} /> <Route path="about" component={About} /> <Route path="inbox" component={Inbox}> <Route path="/messages/:id" component={Message} /> {/* 跳转 /inbox/messages/:id 到 /messages/:id */} <Redirect from="messages/:id" to="/messages/:id" /> </Route> </Route> </Router> ), document.body)
const routeConfig = [ { path: '/', component: App, indexRoute: { component: Dashboard }, childRoutes: [ { path: 'about', component: About }, { path: 'inbox', component: Inbox, childRoutes: [ { path: '/messages/:id', component: Message }, { path: 'messages/:id', onEnter: function (nextState, replaceState) { replaceState(null, '/messages/' + nextState.params.id) } } ] } ] } ] React.render(<Router routes={routeConfig} />, document.body)