简体   繁体   中英

Best practice for handling form submission in React + Typescript

I am refactoring a lot of my code to TypeScript, having just really started to get to grips with TS. When TS forces the HTML element type on the React event, it has made be think about how I create my forms and their submission event handling.

I have always used a <button /> element with a onClick={this.handleSubmission} event handler attached to it. Now, the HTML element type specifying on the React event has made me think that there seems to be two main ways to handle form submission - by capturing the click event on a submission button (as above) or by capturing the onSubmit event on the form itself. These would seem to be typed the following in TypeScript: -

(e: React.MouseEvent<HTMLButtonElement>)
(e: React.FormEvent<HTMLFormElement>)

Is there really any difference between the two in terms of best practice? I would assume a submission button click (providing it is a true HTML button element) would always be handled by (e: React.MouseEvent<HTMLButtonElement>) . However, <input type="submit" value="Submit" /> would seem to be (in TS terms) a true FormEvent on HTMLFormElement as it cannot be a button event.

Is there a best practice or technical requirement or is it just down to personal preference? Thanks.

Not to use FormEvent increases concerns, so capturing FormEvent whould save your time. If we decide to use MouseEvent instead of FormEvent , we should care about defaults, by adding e.preventDefault() .

and using type attribute of <button /> will make markups more declarative.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM