如何通过表单外的按钮提交表单? [英] How to submit a form through a button outside the form?
问题描述
我想通过表单外部的按钮提交表单并对该表单进行验证.我正在使用 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属性 元素在同一文档中.如果这个属性不是指定,
元素将与祖先相关联
元素,如果存在的话.该属性使您能够将
元素关联到
元素中的任意位置文档,而不仅仅是
元素的后代.
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a
<form>
element in the same document. If this attribute is not
specified, the <button>
element will be associated to an ancestor
<form>
element, if one exists. This attribute enables you to
associate <button>
elements to <form>
elements anywhere within a
document, not just as descendants of <form>
elements.
— MDN
这篇关于如何通过表单外的按钮提交表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!