临时笔记-react-router
一、基本用法
npm install --save react-router
路由器Router就是React的一个组件
import { Router } from 'react-router';
render(<Router/>, document.getElementById('app'));
Router组件是一个容器,路由要通过Route组件定义:
import { Router, Route, hashHistory } from 'react-router';
render((
<Router history={hashHistory}>
<Route path="/" component={App}/>
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Router>
), document.getElementById('app'));
用户访问根路由/(比如http://www.example.com/)。路由的切换由URL的hash变化决定,举例来说,用户访问http://www.example.com/,实际会看到的是http://www.example.com/#/。上面代码中,用户访问/repos(比如http://localhost:8080/#/repos)时,加载Repos组件;
二、嵌套路由
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Route>
</Router>
用户访问/repos时,会先加载App组件,然后在它的内部再加载Repos组件
<App>
<Repos/>
</App>
注意,被嵌套的组件App要写成:
render() {
return <div> {this.props.children} </div>
}
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}/>
三、path 属性
path属性指定路由的匹配规则,可以省略。这样的话,不管路径是否匹配,总是会加载指定组件:
<Route path="inbox" component={Inbox}>
<Route path="messages/:id" component={Message} />
</Route>
当用户访问/inbox/messages/:id时,会加载下面的组件:
<Inbox>
<Message/>
</Inbox>
现在如果把 path="inbox"去掉,加载结果还是一样的

浙公网安备 33010602011771号