[英]How to route to a page inside a function in React w/ React-Router?
I have a form in my react app that I made w/ bootstrap and react-router.我的反应应用程序中有一个表格,我用引导程序和 react-router 制作。 When the user hits submit, I want them to go to a page, if the credentials are correct, else do nothing.
当用户点击提交时,我希望他们将 go 转到一个页面,如果凭据正确,否则什么也不做。
<button
class="btn btn-primary font-weight-bold"
type="submit"
onClick={handleSubmit}
>
Submit</button>
... ...
function handleSubmit() {
if (credentials.are.correct) {
// go to page here
}
}
Is there a way to do the above in react-router, without installing any third-party software?有没有办法在react-router中做到以上,无需安装任何第三方软件?
Assuming you're all set and have you app wrapped in Router provider you can useHistory
hook.假设您已经准备好并且将应用程序包装在路由器提供程序中,您可以
useHistory
钩子。 Here's an example from react-router-dom docs:这是react-router-dom文档中的一个示例:
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
react-router has very nice documentation on this subject:) react-router 在这个主题上有很好的文档:)
https://reactrouter.com/web/api/Hooks/usehistory https://reactrouter.com/web/api/Hooks/usehistory
just do it like this if you are using hooks如果你使用钩子就这样做
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.