简体   繁体   中英

Can't get e.preventDefault to work with React Typescript

I have a component that looks like this:

const App = (): ReactElement => {
    
    const submitFeedbackHandler = (e: FormEvent): void => {
        e.preventDefault();
        // ...
    }

    return <>
        <form onSubmit={submitFeedbackHandler}>
            // ...
            <button type='submit'>Submit</button>
        </form>
    </>

}

Problem is, no matter how I try to call submitFeedbackHandler from onSubmit it doesn't work. I tried onSubmit={(e) => submitFeedbackHandler(e)} , but no luck either. How can I get this to work so that I can do e.preventDefault() ?

This might give some headache to inexperienced React developers like myself, so here's the answer to the problem:

I had added the required tag to some inputs in the form. Oddly enough, this stops onSubmit completely from being called. Even simply calling onSubmit = {() => console.log('onSubmit!')} didn't work, so I removed all the required tags from the inputs within the form and it works fine now. I'll do validation of empty fields myself in that case instead of relying on the required tag on inputs.

I think it has to do with controlled and uncontrolled components in React. Will do further research to see exactly what causes this. Thank you @Julius Guevarra for your help.

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