1、安装使用
$ npm install -S react-router
import { Router, Route, hashHistory } from 'react-router';render((<Router history={hashHistory}><Route path="/" component={App}/></Router>
), document.getElementById('app')); 1.1、版本问题
react-router 有多个版本,2.x/3.x - 4.x版本有比较大的改动,并且互相不兼容,2.x/3.x 和 4.x 版本的语法有非常大的不同。并且 react-router 和 react 的某些版本也会有冲突
目前使用 react-router 的 3.x 版本下面的版本可以运行成功。
"dependencies": {"react": "^16.2.0","react-dom": "^16.2.0","react-router": "^3.0.2","react-scripts": "3.1.1" }
2、Router 组件
2.1、JSX 的 Route 组件实现路由
路由器Router就是React的一个组件。Router组件本身只是一个容器,真正的路由要通过Route组件定义。
//入口文件 index.js import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, hashHistory } from 'react-router';ReactDOM.render((<Router history={hashHistory}><Route path="/" component={App}><Route path="/repos" component={Repos}/></Route> </Router> ), document.getElementById('app'));
2.1、route 数组对象实现路由
子路由也可以不写在Router组件里面,单独传入Router组件的routes属性。
let routes = <Route path="/" component={App}><Route path="/repos" component={Repos}/>
</Route>;<Router routes={routes} history={browserHistory}/> 或者是更方便的写法(推荐写法):
const routes = [{path: '/',component: App,indexRoute: { component: DefaultComponent },childRoutes: [{ path: 'about', component: About },{ path: 'inbox', component: Inbox },] }]React.render(<Router routes={routes} />, document.body)
3、路径匹配的组件
react-router 是按 URL 来匹配组件的。
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 匹配到某个组件,并且 URL 上并没有该组件的上层组件(即包含着它的上层 Route),此时仍然会匹配到该组件的上层 Route。
比如下面:用绝对路径表示 Message 组件,当 URL 是 /message/aaa 时,仍会匹配到 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)

想要在某组件内渲染它的下层即子路由,在组件内使用 {this.props.children} 语法。