React-router

React-router
市場上的react-router的版本有一、二、三、4,1-3的差異不大,使用於16.0.0如下的版本

 

react-router 4.0 適用於16.0.0以上

 

在這裏使用15.6.1的react。這個版本的react容許使用React.createClass來建立組件,在16以上只能使用class類的方式來建立

 

1. 渲染根組件的時候,最外層包裹上Router組件,在其上能夠設置history屬性,值能夠是hashHistory||browserHistory

 

當值爲hashHistory的時候,url的變化爲hash值的變化,router會去檢測hash變化來實現組件的切換
 
當值爲browserHistory的時候,url的變化爲path的變化,須要後端進行配置

 

2. Router中使用Route組件來描述每一級路由,Route上有path、component屬性,表明着當path改變成...的時候,就渲染..組件

 

3. 在須要切換路由組件的地方,經過this.props.children來表示對應路由組件

 

4. 在Route中能夠屢次嵌套Route來實現多級路由
```
<Route path="news" component={News}>
//二級路由
<IndexRedirect to="Inside"/>
<Router path="outside" component={Outside} onLeave={()=>{
console.log(arguments)}}/>
<Router path="Inside" component={Inside}/>
</Route>
```

 

5. IndexRoute能夠設置該路由中的默認子路由

 

<IndexRoute component={Home}/>
```
<Route path="news" component={News}>
//二級路由
<IndexRedirect to="Inside"/>
<Router path="outside" component={Outside} onLeave={()=>{
console.log(arguments)}}/>
<Router path="Inside" component={Inside}/>
</Route>
```

 

6. IndexRedirect能夠設置在進入該路由以後立刻跳轉到哪裏
<IndexRedirect to='home'/>
7. 使用Redirect組件能夠作到從一個路由立刻重定向到其餘路由,利用這樣的屬性,當咱們form設置爲'*'的時候,就能夠將匹配不到的路由重定向到某げ路由下

 

<Redirect from="*" to="home"/>

 

8. 能夠在配置Route的時候給path里加入/:param 才表示此路由須要參數
傳入的時候,querystring參數能夠在Link裏的query中傳入和設置,在目標組件中,經過this.props中的,params、routePrams、location等來接收參數
在組件中console.log(this)能夠打印出掛在的數據
```
<Route path="detail/:id" component={Detail}/>
<Link query={{text:item.text}} to={`/detail/${item.id}`}>{item.text}</Link>
```

 

9. 能夠經過過Router傳入routes參數,值爲數組,來設置路由配置:
```
const routeConfig = [
{ path: '/',
component: App,
indexRoute: { component: Home },
childRoutes: [
{ path: 'home', component: Home },
{ path: 'news',
component: News,
childRoutes: [
{ path: 'inside', component: Inside },
{ path: 'outside',component:Outside}
]
},
{ path: 'detail/:id', component: Detail },
{path:'*',component:Home}
]
}
]


ReactDOM.render(
    
    <Router routes={routeConfig} history={hashHistory}></Router>
    ,document.getElementById('app'))


```

 

10. 編程式導航
* 在路由組件中經過this.props.history獲取到history對象,利用裏面push、replace、go、goBack方法來進行隱式跳轉

 

* 能夠從react-router中引入browserHistory或者hashHistory調用裏面的push、replace、go、goBack方法來進行隱式跳轉

 

11. 能夠經過在路由配置上設置 onLeave和onEnter路由鉤子來監聽路由的變化

 

12. 給路由添加樣式;使用activeClassName或者activeStyle

 

```
<Link activeClassName = {'active'} to={item.path} key={item.id}>{item.text}</Link>
```
相關文章
相關標籤/搜索