简体   繁体   English

如何将 handleSubmit 表单函数变成可重用的函数

[英]How to turn a handleSubmit form function into a reusable one

I'm using the React-Bootstrap handleSubmit function to validate a form , submit it , and at the same time call sign() to register my user.我正在使用 React-Bootstrap handleSubmit函数来验证表单,提交它,同时调用sign()来注册我的用户。 Since I will be using a similar form to login the user (just changing the function that gets called inside), and probably in more views, I would like to "outsource" this function, turn it into a reusable one, put in a different file, and call it when needed, passing the arguments required , to make my code cleaner and less repetitive.由于我将使用类似的表单来登录用户(只是更改内部调用的函数),并且可能在更多视图中,我想“外包”这个函数,把它变成一个可重用的,放入一个不同的文件,并在需要时调用它,传递所需的参数,以使我的代码更清晰,更少重复。 But I am quite lost about where to start and how I should do it.但是我对从哪里开始以及应该如何做感到很迷茫。 Any help is much appreciated.任何帮助深表感谢。

In my SignUp.jsx component :在我的SignUp.jsx组件中:

import { useState, useContext } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";

function SignUp() {
  const [validated, setValidated] = useState(false);

  const handleSubmit = (e) => {
    const form = e.currentTarget;
    console.log(form);
    if (form.checkValidity() === false) {
      e.preventDefault();
      e.stopPropagation();
    }
    setValidated(true);
    if (form.checkValidity() === true) {
      e.preventDefault();
      sign();
    }
  };
const sign = () => {
    console.log("user signed up");
  }
  const handleChangeHandler = (e) => {
    setNewUser({ ...newUser, [e.target.name]: e.target.value });
  };


// I omitted many Form fields to reduce the code
  return (
    <div className="containerSignUp">
      <div className="innerContainerSignUp">
        <h1>Sign Up</h1>
        <Form noValidate validated={validated} onSubmit={handleSubmit}>
          <Row>
            <Col>
              <Form.Group className="mb-3" controlId="formBasicUserName">
                <Form.Label>Username</Form.Label>
                <Form.Control
                  required
                  name="userName"
                  value={newUser.userName ? newUser.userName : ""}
                  type="text"
                  onChange={handleChangeHandler}
                />
                <Form.Control.Feedback type="invalid">
                  Please pick a user name.
                </Form.Control.Feedback>
              </Form.Group>
            </Col>
          </Row>
          <Button type="submit" className="signButton">
            Signup
          </Button>
        </Form>
      </div>
    </div>
  );
}

export default SignUp;

My attempt : I created a file validateForm.js :我的尝试:我创建了一个文件validateForm.js

const handleSubmit = (event, func) => {
  // const [validated, setValidated] = useState(false); // I cannot use a state outside a react component.

  const form = e.currentTarget;
  console.log("form", form);

  if (form.checkValidity() === false) {
    e.preventDefault();
    e.stopPropagation();
  }
  setValidated(true);
  if (form.checkValidity() === true) {
    e.preventDefault();
    func();
  }
};

export { handleSubmit };

In signUp.jsx I import it, and call it :signUp.jsx我导入它,并调用它:

import { handleSubmit } from "../utils/validateForm";

And call it when I submit the form :并在我提交表单时调用它:

<Form noValidate validated={validated}
      onSubmit={(e) => {
            handleSubmit(e, sign, setValidated(true));}}>

You can achieve this using a custom hook:您可以使用自定义挂钩来实现此目的:

useHandleSubmit.js使用HandleSubmit.js

const useHandleSubmit() {
    const [validated, setValidated] = useState(false);

    const handleSubmit = (event, func) => {

      const form = event.currentTarget;
      console.log("form", form);

      if (form.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
      }
      // maybe you must move this inside the next `if`, otherwise move it to the end
      setValidated(true);
      if (form.checkValidity() === true) {
        event.preventDefault();
        func();
      }
    };

    return { handleSubmit, validated };

}

export default useHandleSubmit;

In signUp.jsx :signUp.jsx

import useHandleSubmit from '../utils/useHandleSubmit';

...

const { handleSubmit, validated } = useHandleSubmit();

...

<Form noValidate validated={validated}
      onSubmit={(e) => {
            handleSubmit(e, sign}}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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