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} 語法。