ReactRouter5.1.0使⽤useHistory做页⾯跳转导航的实现⽬录
1.使⽤withRouter组件
2、使⽤Route标签
ReactRouter5.1.0使⽤useHistory
在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>
)
})
引⼊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'
2、使⽤Route标签
在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 5.1.0使⽤useHistory
react router6从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页⾯跳转导航内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。