React Bootstrap,通过 React Hooks 提交表单

IT技术 reactjs
2021-05-11 12:37:13

我有一个封装在功能组件中的 React-Bootstrap 表单,我希望提交此表单并让onSubmit该组件处理事件。

但是,我无法弄清楚 , 的组合useRefcreateRef或者forwardRef用来适当地调用submit表单上的 :

登录表单.js

const LoginForm = (props) => {
    const onSubmit = (e) => {
        e.preventDefault()
    }

  return (
    <Form onSubmit={onSubmit} className="form-custom-margin">
      //...
    </Form>
  )
}

export default LoginForm;

MyModal.js

const Modal = (props) => {

  // trying to figure out how to establish a ref?

  const handleActionClick(e){
   // want to call LoginForm and "submit" the form and have `onSubmit` method run
  }

  return (
   <Modal>
     <Modal.Body>
      <LoginForm />
     <Modal.Body>
     <Modal.Footer>
      <Button variant="primary" onClick={handleActionClick}>Login</Button>
     </Modal.Footer>
   </Modal>
  )
}
1个回答

我会采用这种方法,利用 html5 中的 form 属性

在表格上:

import React from "react";

import { Form } from "react-bootstrap";

export default function LoginForm({ handleSubmit }) {
  return (
   // Remember to pass an id that will be referenced on the submit button
    <Form onSubmit={handleSubmit} id="myForm">
      { /* Your Form JSX */}
    </Form>
  );
}

现在您已经为表单分配了一个 id 并且您正在接受一个 onSubmit 函数作为props,您可以执行以下操作:

import React from "react";
import { Button, Modal } from "react-bootstrap";
import FormExample from "./Form";

export default function ModalExample() {
  const [show, setShow] = React.useState(false);

  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  // Pass this callback to the LoginForm
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Form was submitted, now the modal can be closed");
    handleClose();
  };

  return (
    <>
      <Button variant="primary" onClick={handleShow}>
        Launch demo modal
      </Button>

      <Modal show={show} onHide={handleClose}>
        <Modal.Body>
          <LoginForm handleSubmit={handleSubmit} />
        </Modal.Body>
        <Modal.Footer>
         {/* Here the form attribute is referencing the form with the id myForm which is the LoginForm */}
          <Button variant="primary" type="submit" form="myForm">
            Login
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}

这里最重要的部分是我们正在为表单的 onSubmit 处理程序创建一个回调,我们将传递一个 prop。其次请注意,模态页脚有一个带有form属性的按钮,在这种情况下,它将引用您在 Form 组件上添加的 form id 属性。

这是一个快速沙箱,以防您想查看它的实际效果:https : //codesandbox.io/s/nervous-banzai-oockb