我需要以编程方式在单击div元素时调用表单的onsubmit事件。我不想实际提交表格。我只想调用onSubmit事件。我如何实现这一目标?
<form onSubmit={(event)=> {event.preventDefault();this.submitFunction()}>
<ButtonWithIcon onClick={this.onClick} type="submit">
</div>
</form>
onClick=()=> { //need to call the call the onsubmit event }
ButtonWithIcon是一个自定义组件,它具有以及图标。因此,点击图标将不会提交表单。点击图标,我需要
{(event)=> {event.preventDefault();this.submitFunction()} to execute
答案 0 :(得分:0)
查找示例here。关键是将事件处理程序附加到提交表单的div,即<div onClick={this.handleSubmit}>SOME DIV</div>
。
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}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
render(<NameForm />, document.getElementById("root"));