【问题标题】:How to route user after form validation in react functional component如何在反应功能组件中的表单验证后路由用户
【发布时间】:2022-01-09 10:04:55
【问题描述】:

我用链接标签敲击按钮,但是当我点击它时,它直接跳转该页面而没有验证,我使用了 react-bootstrap 表单进行验证。

    const SingIn = () => {
  return (
    <Form className="SingIn">
      <Form.Group className="mb-3" controlId="formBasicEmail">
        <Form.Label>Email address</Form.Label>
        <Form.Control type="email" placeholder="Enter email" required />
        <Form.Text className="text-muted">
          We'll never share your email with anyone else.
        </Form.Text>
      </Form.Group>

      <Form.Group className="mb-3" controlId="formBasicPassword">
        <Form.Label>Password</Form.Label>
        <Form.Control type="password" placeholder="Password" required />
      </Form.Group>
      <Form.Group className="mb-3" controlId="formBasicCheckbox">
        <Form.Check type="checkbox" label="Check me out" />
      </Form.Group>

      <Link to="/movies">
        <Button variant="primary" type="submit">
          Submit
        </Button>
      </Link>

    </Form>
  );
};    

【问题讨论】:

  • 请给我们一些代码。您要验证的内容以及您的路由方式。

标签: reactjs validation routes react-router


【解决方案1】:

我认为您正在尝试在验证后更改路线。 在反应中有两种方法可以做到这一点。 在我们开始之前请记住,在这两种情况下您都不需要链接标签:

<button onClick={handleClick}>click</button>

现在您可以在 handleClick 函数中尝试以下方法之一:

1- 如果你使用 react-router-dom:

首先导入 useHistory 钩子

const history = useHistory()

在你的 handleClick 函数中写:

  const handleClick = () => {
    //validate here
    history.push('/route')
  }

2- 如果你没有使用 react-router-dom:

  const handleClick = () => {
    //validate here
    window.location.href = '/route'
  }

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 2021-08-09
    • 2019-10-02
    • 2021-11-04
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多