0
点赞
收藏
分享

微信扫一扫

react路由-react路由的跳转以及路由信息

课程目标

  1. 熟悉掌握路由的配置
  2. 熟悉掌握跳转路由的方式
  3. 熟悉掌握路由跳转传参的方式
  4. 可以根据对其的理解封装一个类似Vue的router-view

知识点

  1. 路由的配置属性
  • 路由配置属性主要有 path、name、component 等。
    path:组件相对路径
    name:组件路径别名
    component:组件地址
    在路由配置中,有两个属性 exact 和 strict 表示路径匹配。
    “/detail” exact 属性为 true 时匹配的路由有:"/detail/",
    但是 url 中有 “/detail/” 匹配不到。
    “/detail” strict 属性为 true 时匹配的路由有:"/detail",
    但是 “/detail/” 可以被匹配到。
    综上所述,要想严格匹配,就需要将 exact 和 strict 都设为 true
  1. 路由的跳转形式
  • Link 或者 NavLink形式,实质是个 a 标签。区别是后者可以切换时改变样式,用法如下:

<ul>
<li><NavLink exact to="/" activeStyle={{
fontWeight: 'bold',
color: 'red'
}}>
home</NavLink>
</li>
<li><NavLink exact to="/detail" activeStyle={{
fontWeight: 'bold',
color: 'red'
}}>
detail</NavLink>
</li>
</ul>

  • 使用点击事件,用法如下:

<ul>
<li onClick={() => this.props.history.push({pathname:'detail'})}><div>home</div>
</li>
<li onClick={() => this.props.history.push({pathname:'home'})}><div>detail</div>
</li>
</ul>

  1. 跳转传参
  • 直接Link属性传递

<ul>
<li><NavLink exact to="/" activeStyle={{
fontWeight: 'bold',
color: 'red'
}}>
home</NavLink>
</li>
<li><NavLink exact to={{pathname:'detail',state:{id:2}}} activeStyle={{
fontWeight: 'bold',
color: 'red'
}}>
detail</NavLink>
</li>
</ul>

  • 事件跳转传参

<ul>
<li onClick={() => this.props.history.push({pathname:'detail',state:{id:1}})}><div>home</div>
</li>
<li onClick={() => this.props.history.push({pathname:'home',state:{
id:0}})}><div>detail</div>
</li>
</ul>

// 获取参数
this.props.history.location.state

  1. 传递的参数分类
1.使用query传递  
this.props.history.push({ pathname : '/access_control/role/roleEdit',query:{ aa: 'aa'} })
 获取参数:
this.props.location.query.aa
2.使用state传递
 this.props.history.push({ pathname : '/access_control/role/roleEdit',state:{ aa: 'aa'} })
 获取参数:
this.props.location.state.aa


state传的参数是加密的,query传的参数是公开的,在地址栏
  1. 封装RouterView
class RouterView extends Component {
render () {
let {
routes
} = this.props;
let redir = routes && routes.length > 0 && routes.filter((v, i) => {
return v.redirect
})
let renderRedir = redir.length > 0 && redir.map((v, i) => {
return <Redirect from={v.path} to={v.redirect} key={i} />
})
return (
<Switch>
{
routes && routes.length > 0 && routes.map((v, i) => {
if (v.component) {
return <Route key={i} path={v.path} component={(props) => {
return <v.component routes={v.children} {...props} />
}} />
}
}).concat(renderRedir)
}
</Switch>


)

举报

相关推荐

0 条评论