繁体   English   中英

如何在带有 React-Router 的 React 中路由到 function 内的页面?

[英]How to route to a page inside a function in React w/ React-Router?

我的反应应用程序中有一个表格,我用引导程序和 react-router 制作。 当用户点击提交时,我希望他们将 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
  }
}

有没有办法在react-router中做到以上,无需安装任何第三方软件?

在这里您可以阅读如何使用history.push("route")方法在您的代码中使用它。 因此,您只需检查凭据是否正确,如果是,您只需执行history.push到您想要的路线。

假设您已经准备好并且将应用程序包装在路由器提供程序中,您可以useHistory钩子。 这是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 在这个主题上有很好的文档:)

https://reactrouter.com/web/api/Hooks/usehistory

如果你使用钩子就这样做

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM