React-router的基本使用

一、安裝使用

$ 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.一、版本問題

react-router 有多個版本,2.x/3.x  - 4.x版本有比較大的改動,而且互相不兼容,2.x/3.x 和 4.x 版本的語法有很是大的不一樣。而且 react-router 和 react 的某些版本也會有衝突react

目前使用 react-router 的 3.x 版本下面的版本能夠運行成功。npm

"dependencies": {
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-router": "^3.0.2",
    "react-scripts": "3.1.1"
}

二、Router 組件

2.一、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.一、route 數組對象實現路由

子路由也能夠不寫在Router組件裏面,單獨傳入Router組件的routes屬性。react-router

let routes = <Route path="/" component={App}>
  <Route path="/repos" component={Repos}/>
</Route>;

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

或者是更方便的寫法(推薦寫法):app

const routes = [{
  path: '/',
  component: App,
  indexRoute: { component: DefaultComponent },
  childRoutes: [
    { path: 'about', component: About },
    { path: 'inbox', component: Inbox },
  ]
}]

React.render(<Router routes={routes} />, document.body)

 

三、路徑匹配的組件

react-router 是按 URL 來匹配組件的。dom

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。this

好比下面:用絕對路徑表示 Message 組件,當 URL 是 /message/aaa 時,仍會匹配到 APP 和 Inbox 組件,而後再是 Message 組件。spa

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

相關文章
相關標籤/搜索