React表单onSubmit函数未触发问题排查求助
Hey there, let's break down why your onSubmitForm function isn't triggering (and why that console log isn't showing up) — I spotted two key issues in your code:
1. The submit button has an invalid readOnly attribute
The <button> element doesn't support the readOnly property — that's meant for input fields like <input> or <textarea>. Adding it to your submit button is messing with its behavior, preventing it from triggering the form's submit event entirely.
Fix it by removing readOnly and adding visible button text (right now your button is self-closing with no text, so users might not even know to click it!):
<button type='submit' name='Submit' className='btn btn-primary item_cta'>Subscribe</button>
2. You're initializing FormData with the wrong value
In your onSubmitForm function, you're doing new FormData(e) — but e is the submit event object, not the form element itself. FormData needs the actual form DOM node to collect input values correctly. Even if the submit event did fire, this would create an empty FormData object and likely cause errors later.
Update the FormData line to use the event's target (which is the form element):
let formData = new FormData(e.target)
Full Fixed Snippets
Corrected Submit Button
<button type='submit' name='Submit' className='btn btn-primary item_cta'>Subscribe</button>
Updated onSubmitForm Function
onSubmitForm (e) { console.log('function has run'); e.preventDefault() let formData = new FormData(e.target) // Changed to e.target here const { formAction } = this.props const requestOptions = { method: 'POST', body: formData } fetch(formAction, requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)) }
After making these two changes, your submit event should fire properly, and you'll see that "function has run" log in your console. If you still run into issues, check the browser console for other errors (like if formAction isn't being passed correctly as a prop) — also, make sure your inputs meet the required validation rules, since browsers block form submission if required fields are empty (with a default warning).
内容的提问来源于stack exchange,提问作者user2953989

