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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

嚣张.miner   2021-11-12 我要评论
想了解React Router 5.1.0使用useHistory做页面跳转导航的实现的相关内容吗,嚣张.miner在本文为您仔细讲解ReactRouter useHistory页面跳转导航的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:ReactRouter,useHistory页面跳转导航,ReactRouter,页面跳转,下面大家一起来学习吧。

在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>

  )
})

image.jpg

引入 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)

image.jpg

引入: import ButtonWithRouter from ‘./buttonWithRouter'

2、使用Route标签

在route入口

image.jpg

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>
    )
  }} />
)

image.jpg

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>
  )
}

image.jpg

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们