• 如何使用在 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
      })
    }
    不忘初心,不负梦想
  • 相关阅读:
    Java web实验 Login.jsp session属性设置和获取
    Java web实验Outapp.jsp
    Java web实验Accept.jsp
    Java web实验Register.jsp
    Java web实验 Redirect.jsp
    requestAPP1.jps
    out对象
    Request获取请求路径方法介绍
    数据流图
    web应用程序的请求和响应
  • 原文地址:https://www.cnblogs.com/panrui1994/p/11865650.html
Copyright © 2020-2023  润新知