React Router 5.1.0使用useHistory做頁(yè)面跳轉(zhuǎn)導(dǎo)航的實(shí)現(xiàn)
在React Router v4中 可以使用
- withRouter組件
- 使用標(biāo)簽
1.使用withRouter組件
withRouter組件將注入history對(duì)象作為該組件的屬性
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標(biāo)簽
在route入口

Route組件不僅用于匹配位置。 您可以渲染無(wú)路徑的路由,它始終與當(dāng)前位置匹配。 Route組件傳遞與withRouter相同的屬性,因此能夠通過(guò)history的屬性訪問(wèn)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 Router v5.1.0開始,新增了useHistory鉤子(hook),如果是使用React >16.8.0,使用useHistory即可實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)
export const ButtonWithRouter = () => {
const history = useHistory();
console.log('history', history)
return (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
)
}

到此這篇關(guān)于React Router 5.1.0使用useHistory做頁(yè)面跳轉(zhuǎn)導(dǎo)航的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)ReactRouter useHistory頁(yè)面跳轉(zhuǎn)導(dǎo)航內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React Native設(shè)備信息查看調(diào)試詳解
這篇文章主要為大家介紹了React Native設(shè)備信息查看調(diào)試詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
React創(chuàng)建虛擬DOM的兩種方式小結(jié)
本文主要介紹了兩種創(chuàng)建React虛擬DOM的方式,包括JS方式和jsx方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01
解決React報(bào)錯(cuò)Cannot assign to 'current'
這篇文章主要為大家介紹了React報(bào)錯(cuò)Cannot assign to 'current' because it is a read-only property的解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
react?express實(shí)現(xiàn)webssh?demo解析
這篇文章主要為大家介紹了詳解react?express實(shí)現(xiàn)webssh?demo解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
React項(xiàng)目中服務(wù)器端渲染SSR的實(shí)現(xiàn)與優(yōu)化詳解
在傳統(tǒng)的 React 項(xiàng)目里,頁(yè)面的渲染工作是在瀏覽器里完成的,而服務(wù)器端渲染(SSR)則是讓服務(wù)器先把 React 組件渲染成 HTML 字符串,再把這個(gè) HTML 字符串發(fā)送給瀏覽器,下面我們就來(lái)看看具體實(shí)現(xiàn)方法吧2025-03-03
React新擴(kuò)展函數(shù)setState與lazyLoad及hook介紹
這篇文章主要介紹了React新擴(kuò)展函數(shù)setState與lazyLoad及hook,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-12-12

