React Router 5.1.0使用useHistory做頁面跳轉(zhuǎn)導(dǎo)航的實現(xiàn)
在React Router v4中 可以使用
- withRouter組件
- 使用標(biāo)簽
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標(biāo)簽
在route入口
Route組件不僅用于匹配位置。 您可以渲染無路徑的路由,它始終與當(dāng)前位置匹配。 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 Router v5.1.0開始,新增了useHistory鉤子(hook),如果是使用React >16.8.0,使用useHistory即可實現(xiàn)頁面跳轉(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做頁面跳轉(zhuǎn)導(dǎo)航的實現(xiàn)的文章就介紹到這了,更多相關(guān)ReactRouter useHistory頁面跳轉(zhuǎn)導(dǎo)航內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React創(chuàng)建組件的三種方式及其區(qū)別是什么
在React中,創(chuàng)建組件的三種主要方式是函數(shù)式組件、類組件和使用React Hooks的函數(shù)式組件,本文就詳細(xì)的介紹一下如何使用,感興趣的可以了解一下2023-08-08React+Typescript項目環(huán)境搭建并使用redux環(huán)境的詳細(xì)過程
這篇文章主要介紹了React+Typescript項目環(huán)境搭建并使用redux環(huán)境的詳細(xì)過程,本文通過圖文實例相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09使用React+ts實現(xiàn)無縫滾動的走馬燈詳細(xì)過程
這篇文章主要給大家介紹了關(guān)于使用React+ts實現(xiàn)無縫滾動的走馬燈詳細(xì)過程,文中給出了詳細(xì)的代碼示例以及圖文教程,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2023-08-08如何不使用eject修改create-react-app的配置
許多剛開始接觸create-react-app框架的同學(xué),不免都會有個疑問:如何在不執(zhí)行eject操作的同時,修改create-react-app的配置。2021-04-04React實現(xiàn)錨點跳轉(zhuǎn)組件附帶吸頂效果的示例代碼
這篇文章主要為大家詳細(xì)介紹了React如何實現(xiàn)移動端錨點跳轉(zhuǎn)組件附帶吸頂效果,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-01-01