[英]How do I use history prop with other props
I'm using react-router-dom
with react
.我正在使用
react-router-dom
和react
。 I'm trying to have other props with the history prop
我正在尝试使用
history prop
获得其他道具
import React from 'react';
function MyComponent({ history }) {
function redirect() {
history.push('/path');
}
return (
<>
<button onClick={redirect}>Some Button</button>
</>
);
}
export default MyComponent;
This will work, but if I put another prop like this这会起作用,但如果我放另一个这样的道具
function MyComponent({myFunction, history}) {}
This wouldn't work这行不通
Is there any alternatives to this, or am I doing something wrong?有没有其他选择,或者我做错了什么?
Instead you can useuseHistory()
hook from react-router-dom .相反,您可以使用react-router-dom中的
useHistory()
钩子。 Read from the documentation:从文档中阅读:
The
useHistory
hook gives you access to the history instance that you may use to navigate.useHistory
挂钩使您可以访问可用于导航的历史实例。
Try as the following:尝试如下:
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;
If you need a fully working example, please find one of my GitHub repositiries below: https://github.com/norbitrial/react-router-programmatically-redirect-examples如果您需要一个完整的示例,请在下面找到我的 GitHub 存储库之一: https://github.com/norbitrial/react-router-programmatically-redirect-examples
I suggest to take a look at this file from there.我建议从那里看一下这个文件。 I have already included the essential working example above in my code snippet.
我已经在我的代码片段中包含了上面的基本工作示例。
I hope this helps!我希望这有帮助!
Try this - you can receive as many props as you want.试试这个 - 你可以收到尽可能多的道具。
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.