简体   繁体   中英

onClick vs onSubmit in React

I have a simple input in react that won't work with onSubmit but with onClick . Why is that? Here is the link to an example.

 const styles = { fontFamily: 'sans-serif', textAlign: 'center', }; const clicked = e => { alert("Hi") } const App = () => ( <div style={styles}> <input type='submit' value='click' onSubmit={clicked}/> </div> ); ReactDOM.render(<App />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root" />

onSubmit is a prop for <form> , you should add the handler on to that element:

<form onSubmit={onSubmit}>
  <input ... />
</form>

我认为它需要在<form></form>才能提交工作

Because you're not submitting anything. onSubmit is for submitting forms...

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