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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理