简体   繁体   English

点击提交按钮时,React 表单不调用提交功能

[英]React form not calling submit function upon submit button click

I have a straight forward react form below which called a handlesubmit function when the submit button is clicked.我有一个直接的反应表单,当点击提交按钮时,它会调用一个 handlesubmit 函数。 However, it seems that there are two issues.但是,似乎有两个问题。 Firstly, the form doesn't validate inputs, and in fact accepts the empty inputs when submitted.首先,表单不验证输入,实际上在提交时接受空输入。 Any help is appreciated please.任何帮助表示赞赏。

import Form from "react-bootstrap/Form"
import Button from "react-bootstrap/Button"
import Col from "react-bootstrap/Col"
import { useState } from "react"


const Register = () => {

    const [validated, setValidated] = useState(false);
    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');

    const handleSubmit = (event) => {
        const form = event.currentTarget;
        console.log("in handlesubmit: " + form.checkValidity())
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
    
        setValidated(true);
        console.log("in handlesubmit: " + validated)
      };

    console.log('First Name: ' + firstName);
    console.log('Last Name: ' + lastName);

    return (
        <div>
            <h1>Registration page</h1>
            <Form noValidated validated={validated} onSubmit={handleSubmit} style={{textAlign:'left'}}>
            <Form.Row>
                <Form.Group as={Col} controlId="formGridFirstName">
                <Form.Label>First name</Form.Label>
                <Form.Control type="text" placeholder="Enter first name" value={firstName} onChange={(e) => setFirstName(e.target.value)}/>
                </Form.Group>

                <Form.Group as={Col} controlId="formGridLastName">
                <Form.Label>Last name</Form.Label>
                <Form.Control type="text" placeholder="Enter last name" value={lastName} onChange={(e) => setLastName(e.target.value)}/>
                </Form.Group>
            </Form.Row>

            <Button variant="primary" type="submit">
                Submit
            </Button>
        </Form>
        </div>
    )
}

export default Register

I think you probably need to add an onclick to your button.我认为您可能需要在按钮上添加一个 onclick。 Try onClick={()=>{}} and see if that's triggers your form onsubmit?试试onClick={()=>{}}看看是否会触发你的表单提交?

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

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