基本使用

使用时,路由器Router就是React的一个组件。

1
2
import { Router } from 'react-router';
render(<Router/>, document.getElementById('app'));

Router组件本身只是一个容器,真正的路由要通过Route组件定义。

1
2
3
4
5
6
7
import { Router, Route, hashHistory } from 'react-router';

render((
<Router history={hashHistory}>
<Route path="/" component={App}/>
</Router>
), document.getElementById('app'));

上面代码中,用户访问根路由/(比如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
2
3
4
5
<Router history={hashHistory}>
<Route path="/" component={App}/>
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Router>

上面代码中,用户访问/repos(比如http://localhost:8080/#/repos)时,加载Repos组件;访问/abouthttp://localhost:8080/#/about)时,加载About组件。

嵌套路由

Route组件还可以嵌套。

1
2
3
4
5
6
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Route>
</Router>

上面代码中,用户访问/repos时,会先加载App组件,然后在它的内部再加载Repos组件。

1
2
3
<App>
<Repos/>
</App>

App组件要写成下面的样子。

1
2
3
4
5
6
7
export default React.createClass({
render() {
return <div>
{this.props.children}
</div>
}
})

上面代码中,App组件的this.props.children属性就是子组件。

子路由也可以不写在Router组件里面,单独传入Router组件的routes属性。

1
2
3
4
5
6
let routes = <Route path="/" component={App}>
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Route>;

<Router routes={routes} history={browserHistory}/>

path 属性

Route组件的path属性指定路由的匹配规则。这个属性是可以省略的,这样的话,不管路径是否匹配,总是会加载指定组件。

1
2
3
<Route path="inbox" component={Inbox}>
<Route path="messages/:id" component={Message} />
</Route>

上面代码中,当用户访问/inbox/messages/:id时,会加载下面的组件

1
2
3
<Inbox>
<Message/>
</Inbox>

如果省略外层Routepath参数,写成下面的样子。

1
2
3
<Route component={Inbox}>
<Route path="inbox/messages/:id" component={Message} />
</Route>

现在用户访问/inbox/messages/:id时,组件加载还是原来的样子。

1
2
3
<Inbox>
<Message/>
</Inbox>