我正在将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}) {}
这不起作用
是否有其他替代方法,或者我做错了什么?
相反,您可以使用useHistory()
挂钩。
尝试以下操作:
import { useHistory } from 'react-router-dom';
function MyComponent({ myFunction }) {
let history = useHistory();
function redirect() {
history.push('/path');
}
return (
<>
<button onClick={redirect}>Some Button</button>
</>
);
}
我希望这会有所帮助!