React Router中withRouter组件的用处和用法是什么
Admin 2022-06-20 群英技术资讯 1121 次浏览
这篇文章将为大家详细讲解有关“React Router中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'
在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 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>
)
}

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了Vue中强制组件重新渲染的正确方法,帮助大家更好的理解和使用vue框架,感兴趣的朋友可以了解下
jQuery中有什么方法增加class的属性?对于jQuery中增加class的属性的方法,这里给大家介绍addClass()方法,这是 jquery提供一个添加class类的方法,接下来我们那就来具体的了解看看,addClass()方法怎样实现增加class。
在本篇文章里小编给大家整理的是一篇关于nodejs插件及用法相关内容,有兴趣的朋友们可以跟着学习参考下。
今天来给大家简单的聊一聊Rx响应式编程,对于Rx响应式编程的学习,Observable的内容是需要掌握了解的,因此下面小编就给大家来介绍一下Observable,有这方面学习需要的朋友可以参考。
文本给大家分享的是js中this和箭头函数,其中关于this关键字是很多新手学习JavaScript时,比较难理解。箭头函数是新增的,小编觉得比较有意思,因此下文给大家介绍一下。对js中this和箭头函数感兴趣的朋友就继续往下看吧。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008