如何通过表单外的按钮提交表单? [英] How to submit a form through a button outside the form?

查看:138
本文介绍了如何通过表单外的按钮提交表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过表单外部的按钮提交表单并对该表单进行验证.我正在使用 react-bootstrap 中的 Form 标签.

I want to submit a form through a button which is outside the form and do the validation to that form. I'm using the Form tag from react-bootstrap.

我的代码没有验证表单

<Form
    noValidate
    validated={validated}
    onSubmit={e=> this.handleSubmit(e)}>

    <Form.Control
        required
        placeholder="Product Name"
        onChange={e => this.setState({name: e.target.value })}
        pattern={"[A-Z a-z]{3,30}"}
    />
</Form>
<button type="button" value="send" onClick={(e) => this.handleSubmit(e)} className={"btn btn-primary"}>Save</button>

handleSubmit(event) {
    const form = event.currentTarget;
    if (form.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
    }
    else
        this.AddProduct();

    this.setState({ validated: true });
}

推荐答案

理想情况下:不要那样做.表单元素是一种有用的结构元素.

Ideally: Don't do that. Form elements are a useful structural element.

失败了.为按钮添加一个 form 属性,其值等于表单的 id 属性.

Failing that. Add a form attribute to the button with the value equal to the id attribute of the form.

表单 HTML5

与按钮关联的表单元素(其表单所有者).属性的值必须是a的id属性

元素在同一文档中.如果这个属性不是指定,
查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆