基本使用
使用时,路由器Router
就是React的一个组件。
1 | import { Router } from 'react-router'; |
Router
组件本身只是一个容器,真正的路由要通过Route
组件定义。
1 | import { Router, Route, hashHistory } from 'react-router'; |
上面代码中,用户访问根路由/
(比如http://www.example.com/
),组件APP
就会加载到document.getElementById('app')
。
你可能还注意到,Router
组件有一个参数history
,它的值hashHistory
表示,路由的切换由URL的hash变化决定,即URL的#
部分发生变化。举例来说,用户访问http://www.example.com/
,实际会看到的是http://www.example.com/#/
。
Route
组件定义了URL路径与组件的对应关系。你可以同时使用多个Route
组件。
1 | <Router history={hashHistory}> |
上面代码中,用户访问/repos
(比如http://localhost:8080/#/repos
)时,加载Repos
组件;访问/about
(http://localhost:8080/#/about
)时,加载About
组件。
嵌套路由
Route
组件还可以嵌套。
1 | <Router history={hashHistory}> |
上面代码中,用户访问/repos
时,会先加载App
组件,然后在它的内部再加载Repos
组件。
1 | <App> |
App
组件要写成下面的样子。
1 | export default React.createClass({ |
上面代码中,App
组件的this.props.children
属性就是子组件。
子路由也可以不写在Router
组件里面,单独传入Router
组件的routes
属性。
1 | let routes = <Route path="/" component={App}> |
path 属性
Route
组件的path
属性指定路由的匹配规则。这个属性是可以省略的,这样的话,不管路径是否匹配,总是会加载指定组件。
1 | <Route path="inbox" component={Inbox}> |
上面代码中,当用户访问/inbox/messages/:id
时,会加载下面的组件
1 | <Inbox> |
如果省略外层Route
的path
参数,写成下面的样子。
1 | <Route component={Inbox}> |
现在用户访问/inbox/messages/:id
时,组件加载还是原来的样子。
1 | <Inbox> |