[英]How do I use history prop with other props
我正在使用react-router-dom
和react
。 我正在嘗試使用history prop
獲得其他道具
import React from 'react';
function MyComponent({ history }) {
function redirect() {
history.push('/path');
}
return (
<>
<button onClick={redirect}>Some Button</button>
</>
);
}
export default MyComponent;
這會起作用,但如果我放另一個這樣的道具
function MyComponent({myFunction, history}) {}
這行不通
有沒有其他選擇,或者我做錯了什么?
相反,您可以使用react-router-dom中的useHistory()
鈎子。 從文檔中閱讀:
useHistory
掛鈎使您可以訪問可用於導航的歷史實例。
嘗試如下:
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
我建議從那里看一下這個文件。 我已經在我的代碼片段中包含了上面的基本工作示例。
我希望這有幫助!
試試這個 - 你可以收到盡可能多的道具。
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.