脚本宝典收集整理的这篇文章主要介绍了React Router 5.1.0使用useHistory做页面跳转导航的实现,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
在React Router v4中 可以使用
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> ) }
到此这篇关于React Router 5.1.0使用useHistory做页面跳转导航的实现的文章就介绍到这了,更多相关ReactRouter useHistory页面跳转导航内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!
以上是脚本宝典为你收集整理的React Router 5.1.0使用useHistory做页面跳转导航的实现全部内容,希望文章能够帮你解决React Router 5.1.0使用useHistory做页面跳转导航的实现所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。