React Router中withRouter组件的用处和用法是什么
Admin 2022-06-20 群英技术资讯 1049 次浏览
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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
ES6增加了for..of循环,用于迭代对象,要求对象必须是可迭代的。可用范围包括数组、Set和Map结构、数组的对象、Generator对象和字符串。
这篇文章我们来了解jQuery如何实现商品筛选功能,如果经常购物的朋友对于商品的筛选功能应该都不陌生吧,能帮助我们快速的找到所需的商品,那么这个功能究竟是如何实现的呢?下文给大家分享了两种实现思路和方法,感兴趣的朋友就继续往下看吧。
在项目开发过程中,因为项目的需要由时候必须要设置弹出的视图,而Angular实现的方式有哪几种呢?今天爱站技术频道小编就为大家带来了Angular弹出模态框的两种方式,一起进入下文学习吧!
Axios 毋庸多说大家在前端开发中常用的一个发送 HTTP 请求的库,用过的都知道,篇文章主要给大家介绍了关于vue中如何简单封装axios的相关资料,需要的朋友可以参考下
这篇文章主要为大家详细介绍了微信小程序自定义Dialog弹框,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008