React-router的基本使用
生活随笔
收集整理的這篇文章主要介紹了
React-router的基本使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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} 語法。
轉載于:https://www.cnblogs.com/wenxuehai/p/11387261.html
總結
以上是生活随笔為你收集整理的React-router的基本使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: React使用的扩展
- 下一篇: Vux的安装使用