zoukankan      html  css  js  c++  java
  • 如何使用在 React Router v4 中以编程的方式进行导航

    1:使用withRouter()高阶函数
    withRouter()高阶函数将注入 history 对象作为组件的 prop。该对象提供了push()和replace()方法,以避免使用上下文
    import { withRouter } from 'react-router-dom' // this also works with 'react-router-native'
    
    const Button = withRouter(({ history }) => (
      <button
        type='button'
        onClick={() => { history.push('/new-location') }}
      >
        {'Click Me!'}
      </button>
    ))
    2:使用<Route>组件和渲染属性模式
    <Route>组件传递与withRouter()相同的属性,因此您将能够通过 history 属性访问到操作历史记录的方法
    import { Route } from 'react-router-dom'
    
    const Button = () => (
      <Route render={({ history }) => (
        <button
          type='button'
          onClick={() => { history.push('/new-location') }}
        >
          {'Click Me!'}
        </button>
      )} />
    )
    3:使用上下文
    const Button = (props, context) => (
      <button
        type='button'
        onClick={() => {
          context.history.push('/new-location')
        }}
      >
        {'Click Me!'}
      </button>
    )
    
    Button.contextTypes = {
      history: React.PropTypes.shape({
        push: React.PropTypes.func.isRequired
      })
    }
    不忘初心,不负梦想
  • 相关阅读:
    OpenSSL证书生成
    支付宝支付流程
    前端获取用户位置信息
    微信公众号开发(三)
    微信公众号开发(二)
    微信公众号开发(一)
    前端优化
    页面自适应
    CSS样式(二)
    CSS样式(一)
  • 原文地址:https://www.cnblogs.com/panrui1994/p/11865650.html
Copyright © 2011-2022 走看看