This is the react code I'm currently using:
import React, { Component } from 'react'
export class AddProduct extends Component {
doSomething(){
console.log('Hello')
}
render() {
return (
<div>
<h3>Product name</h3>
<input type="text" id="product"></input>
<h3>Product price</h3>
<input type="text" id="price"></input>
<input type="submit" id="submit" value="Submit" onSubmit={(e) => {this.doSomething();}}></input>
</div>
)
}
}
export default AddProduct
I'm expecting a 'Hello' output to the terminal when the submit button is pressed however it does not show up. Could anyone help me out?
<input>
elements do not fire a submit
event when clicked, even when inside a form:
document.querySelector('input').addEventListener('submit', () => { alert('submit event seen'); });
<form> <input type="submit"> </form>
A click event would work, though. Change
onSubmit={(e) => {this.doSomething();}}
to
onClick={(e) => {this.doSomething();}}
If your <input>
happens to be inside a form, you could attach a submit
listener to the form instead.
In order to handle a submit event, you must use a <form />
element.
Example:
import React, { Component } from 'react'
class AddProduct extends Component {
doSomething() {
console.log('Hello')
}
render() {
return (
<form onSubmit={(e) => this.doSomething()}>
<h3>Product name</h3>
<input type="text" id="product" />
<h3>Product price</h3>
<input type="text" id="price" />
<input type="submit" id="submit" value="Submit" />
</form>
);
}
}
export default AddProduct;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.