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>
```
相关文章
相关标签/搜索