开发者社区> 问答> 正文

#React 您如何使用React Router v4以编程方式导航?

#React 您如何使用React Router v4以编程方式导航?

展开
收起
因为相信,所以看见。 2020-05-07 20:14:17 620 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    有三种不同的方法可以在组件内实现程序化的路由/导航。

    使用withRouter()高阶函数:

    的withRouter()高阶函数将注入历史记录对象作为组分的道具。该对象提供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>
    ))
    

    使用 component和render props模式:

    该 组件传递与相同的道具withRouter(),因此您将能够通过历史道具访问历史方法。

    import { Route } from 'react-router-dom'
    
    const Button = () => (
      <Route render={({ history }) => (
        <button
          type='button'
          onClick={() => { history.push('/new-location') }}
        >
          {'Click Me!'}
        </button>
      )} />
    )
    

    使用上下文: 不建议使用此选项,并将其视为不稳定的API。

    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
      })
    }
    
    
    2020-05-07 20:16:27
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
利用编译将 Vue 组件转成 React 组件 立即下载
React Native 全量化实践 立即下载
React在大型后台管理项目中的工程实践 立即下载