javascript - 如何通过表单外的按钮提交表单?

标签 javascript reactjs jsx react-bootstrap

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

我的代码未验证表单

<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 });
}

最佳答案

理想情况下:不要这样做。表单元素是有用的结构元素。

失败了。添加form属性值等于 id 的按钮表单的属性。

form HTML5

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

关于javascript - 如何通过表单外的按钮提交表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56025301/

相关文章:

javascript - 窗口.打开 : is it possible open a new window with modify its DOM

javascript - 使用触发器将元素添加到 firebase 实时数据库

node.js - 为什么当我运行 Express 服务器(React.js)时,我的浏览器显示空白页面?

javascript - 如何在 React.js 中获取另一个组件的元素?

javascript - react - Redux 应用程序 : "Invalid attempt to spread non-iterable instance" Issue

javascript - React - 未捕获的类型错误 : Cannot read property 'func' of undefined

javascript - 多个 Google map 无法与 Bootstrap 3 选项卡配合使用

javascript - AngularJS 如何同时放置 ng-class 和 CSS 类

javascript - 使用 React 获取选择值

javascript - React - 调用父组件中的函数来访问状态