华域联盟 JavaScript React Router 5.1.0使用useHistory做页面跳转导航的实现

React Router 5.1.0使用useHistory做页面跳转导航的实现

目录

在React Router v4中 可以使用

  1. withRouter组件
  2. 使用标签

1.使用withRouter组件

withRouter组件将注入history对象作为该组件的属性

import React from 'react'
import { withRouter } from 'react-router-dom'
import { Button } from 'antd'

export const ButtonWithRouter = withRouter(({ history }) => {
  console.log('history', history)
  return (
    <Button
      type='default'
      onClick={() => { history.push('/new-location') }}
    >
      Click Me!
    </Button>

  )
})

引入 import { ButtonWithRouter } from ‘./buttonWithRouter'

或者:

const ButtonWithRouter = (props) => {
  console.log('props', props)
  return (
    <Button
      type='default'
      onClick={() => { props.history.location.push('/new-location') }}
    >
      Click Me!
    </Button>

  )
}

export default withRouter(ButtonWithRouter)

引入: import ButtonWithRouter from ‘./buttonWithRouter'

2、使用Route标签

在route入口

Route组件不仅用于匹配位置。 您可以渲染无路径的路由,它始终与当前位置匹配。 Route组件传递与withRouter相同的属性,因此能够通过history的属性访问history的方法。

so:

export const ButtonWithRouter = () => (
  <Route render={({ history }) => {
    console.log('history', history)
    return (
      <button
        type='button'
        onClick={() => { history.push('/new-location') }}
      >
        Click Me!
      </button>
    )
  }} />
)

React Router 5.1.0使用useHistory

从React Router v5.1.0开始,新增了useHistory钩子(hook),如果是使用React >16.8.0,使用useHistory即可实现页面跳转

export const ButtonWithRouter = () => {
  const history = useHistory();
  console.log('history', history)
  return (
    <button
      type='button'
      onClick={() => { history.push('/new-location') }}
    >
      Click Me!
    </button>
  )
}

到此这篇关于React Router 5.1.0使用useHistory做页面跳转导航的实现的文章就介绍到这了,更多相关ReactRouter useHistory页面跳转导航内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

本文由 华域联盟 原创撰写:华域联盟 » React Router 5.1.0使用useHistory做页面跳转导航的实现

转载请保留出处和原文链接:https://www.cnhackhy.com/146973.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们