im试图找到一种手动触发Submit事件的方法,就像type =“ submit”的按钮一样。 我在此处的另一篇文章中找到了一种方法来执行此操作,但是不幸的是,即使没有在输入中键入任何文本,它也不会检查所需的输入是否包含值并提交表单:
https://codesandbox.io/s/q92855nz3w
或
import React from "react";
import { render } from "react-dom";
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
alert("A name was submitted: " + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div onClick={this.handleSubmit}>SOME DIV</div>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
required
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
render(<NameForm />, document.getElementById("root"));
感谢您的任何帮助!
答案 0 :(得分:0)
找到了我的问题的解决方案:
var form = document.getElementById("form");
form.reportValidity();