2 回答

TA貢獻1797條經(jīng)驗 獲得超6個贊
相反,您可以使用react-router-domuseHistory()中的鉤子。從文檔中閱讀:
該useHistory鉤子使您可以訪問可用于導(dǎo)航的歷史實例。
嘗試如下:
import React from 'react';
import { useHistory } from 'react-router-dom';
function MyComponent({ myFunction }) { // here still you can pass other props
let history = useHistory(); // meanwhile you have the history object
function redirect() {
history.push('/path');
}
return <>
<button onClick={redirect}>Some Button</button>
</>
}
export default MyComponent;
如果您需要一個完整的示例,請在下面找到我的 GitHub 存儲庫之一: https ://github.com/norbitrial/react-router-programmatically-redirect-examples
我建議從那里看一下這個文件。我已經(jīng)在我的代碼片段中包含了上面的基本工作示例。
我希望這有幫助!

TA貢獻1775條經(jīng)驗 獲得超11個贊
試試這個 - 你可以收到盡可能多的道具。
import React from 'react';
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
function redirect() {
history.push('/path');
}
return (
<>
<button onClick={redirect}>Some Button</button>
</>
);
}
export default MyComponent;
添加回答
舉報