zoukankan      html  css  js  c++  java
  • 笔记react router 4(五)

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

    然后,我们就要来聊一聊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}/>
        )
      }
    }
  • 相关阅读:
    多组件共享-vuex
    在子组件中触发事件,传值给父组件-vue
    在父组件中,直接获取子组件数据-vue
    非父子组件通过事件传值-vue
    在父组件中,传值给子组件-vue
    MVVM
    Virtual DOM-渲染函数render -vue
    duilib入门简明教程 -- VS环境配置(2) (转)
    duilib入门简明教程 -- 前言(1) (转)
    【CDockablePane】关于CDockablePane
  • 原文地址:https://www.cnblogs.com/zyl-Tara/p/9686049.html
Copyright © 2011-2022 走看看