最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onClick vs onSubmit in React - Stack Overflow

programmeradmin1浏览0评论

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=".1.0/react.min.js"></script>
<script src=".1.0/react-dom.min.js"></script>
<div id="root" />

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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />

Share Improve this question edited Feb 13, 2018 at 0:58 Austin Greco 33.6k6 gold badges59 silver badges61 bronze badges asked Feb 13, 2018 at 0:52 Siya MzamSiya Mzam 4,7051 gold badge31 silver badges46 bronze badges 2
  • please post the relevant code in the question – Chaim Friedman Commented Feb 13, 2018 at 0:53
  • I have attached the link to a working example. – Siya Mzam Commented Feb 13, 2018 at 0:54
Add a ment  | 

3 Answers 3

Reset to default 3

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

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

I think it needs to be in a <form></form> for submit to work

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

发布评论

评论列表(0)

  1. 暂无评论