React Router 5.1.0使用useHistory做頁面跳轉(zhuǎn)導航的實現(xiàn)
在React Router v4中 可以使用
- withRouter組件
- 使用標簽
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 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>
)
}

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

