react-router4学习

2018-12-05  本文已影响0人  依然还是或者其他

近期学习了react相关知识,记录一下。

1.一般性使用

官方react-router 文档
https://reacttraining.com/react-router/web/example/basic

简单基本的用户在basic中已有比较好的介绍了。

如果要想让li标签根据当前路由显示不同的样式的话,需要用到NavLink,
在文档的列表中也有关于NavLink的API介绍 ,其中可以通过activeClassName
属性来设置路由触发的样式,也可以通过activeStyle来设置。

2.关于重定向

重定向需要使用Redirect组件来实现,对应文档中有相关介绍。

下面也是重定向比较常见的一种形式,在Router 组件的render属性中被调用。
需要注意的是:重定向需要写在最后,不然会发生报错。

<div>
      <HomeSearch/>
      <HomeNav data={initData} clickCallBack={this.clickHandler}/>

      <Route path={"/home"} component={HomeContent} />
      <Route path={"/channel/:type"} key={this.state.key} component={ContentRoute} />
      <Route exact path={"/"} render={()=><Redirect to={"/home"}/>}/>
</div>
3.传参

传参,如上图path={"/channel/:type"},
获取参数可以通过props.match来获取

4.路由跳转

自动跳转:路由跳转可以通过Link或NAVLink来实现
手动跳转:
引入import {withRouter} from 'react-router-dom'
在组件外围包一层withRouter,即export default withRouter(TestComponent)
然后在TestComponent通过调用this.props.history.push(/recommend/${item.dissid});进行跳转

注:withRouter(TestComponent) 如有看不懂,请查看高阶组件相关知识

5.结合react-router-config的使用

如果之前使用过vue-router这样的形式,也想react-router 有那样的路由配置管理,可以使用react-router-config这个包。
官方文档中的一个例子,如下,写一点注释
官方地址:https://www.npmjs.com/package/react-router-config

import { renderRoutes } from 'react-router-config'
 //路由配置,可单独写成一个文件
const routes = [
  { component: Root,
    routes: [
      { path: '/',
        exact: true,
        component: Home
      },
      { path: '/child/:id',
        component: Child,
        routes: [
          { path: '/child/:id/grand-child',
            component: GrandChild
          }
        ]
      }
    ]
  }
]
 
const Root = ({ route }) => (
  <div>
    <h1>Root</h1>
    {/* child routes won't render without this */}
    {renderRoutes(route.routes)}
  </div>
)
 
const Home = ({ route }) => (
  <div>
    <h2>Home</h2>
  </div>
)
 
const Child = ({ route }) => (
  <div>
    <h2>Child</h2>
    {/* child routes won't render without this */}
    {renderRoutes(route.routes, { someProp: 'these extra props are optional' })}
  </div>
)
 
const GrandChild = ({ someProp }) => (
  <div>
    <h3>Grand Child</h3>
    <div>{someProp}</div>
  </div>
)
 
 //BrowserRouter 下只能有一个子元素,若有两个并列的子组件,可以先套一层div
ReactDOM.render((
  <BrowserRouter>
    {/* kick it all off with the root route */}
    {renderRoutes(routes)}
  </BrowserRouter>
), document.getElementById('root'))

如果要实现按需加载,可以使用react-loadable,使用方法请参考官方。

上一篇 下一篇

猜你喜欢

热点阅读