首页 > 其他 > 详细

你应该知道的react router 4(五)

时间:2018-09-21 14:29:58      阅读:171      评论:0      收藏:0      [点我收藏+]

  或许,你觉得我麻烦,明明一篇文章可以搞定的内容,非要写几篇。是不是正在吐槽我?没关系,我的目的达到了。手动傲娇( ̄? ̄)

然后,我们就要来聊一聊withRouter了。

我们都知道,当我在访问路由配置文件中的组件,通常我们称之为路由组件时,可以从他的props中访问到路由对象。如,location。但是,没有声明在路由中的组件,通常我们称之为非路由组件,比如路由组件中我们使用到的外部组件时,我们需要用到路由对象该怎么办呢?

在3.X中,我们要在非路由组件中使用history对象,需要手动引入history,就像这样,

import createHistory from ‘history/createBrowserHistory‘
const history = createHistory()

或者,我们在路由组件中将获取到的路由对象手动传递给外部组件。

<Parent>
    <Child routeProps = {this.props.location} />
</Parent>

再或者,我们可以使用H5的history API。

window.location

但是4.X中我们可以不用那么麻烦了,直接一个withRouter包裹你的外部组件,即可通过props访问到location, router及history等对象。

就像这样,

import React from ‘react‘
import PropTypes from ‘prop-types‘
import { withRouter } from ‘react-router‘

class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}

const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
来自:https://reacttraining.com/react-router/web/api/withRouter

  接着再来看, component.WrappedComponent

// MyComponent.js
export default withRouter(MyComponent)

// MyComponent.test.js
import MyComponent from ‘./MyComponent‘
render(<MyComponent.WrappedComponent location={{...}} ... />)

它用于创建一个包装组件上,通常用于测试。

  wrappedComponnetRef这个函数的作用是refs获取组件实例。

class Container extends React.Component {
  componentDidMount() {
    this.component.doSomething()
  }

  render() {
    return (
      <MyComponent wrappedComponentRef={c => this.component = c}/>
    )
  }
}

 

你应该知道的react router 4(五)

原文:https://www.cnblogs.com/zyl-Tara/p/9686049.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!