[英]form onSubmit vs onClick
<form>
<input />
<button
onClick={e => {
e.preventDefault();
alert("clicked");
}}
>
click
</button>
</form>
If I move the onClick
handler to form
's onSubmit
, I will get the exact same behavior. 如果我将
onClick
处理程序移动到form
的onSubmit
,我将得到完全相同的行为。
Most answers I googled suggested that the difference is onClick
will not react to submitting form via return
key press but that's not true as seen in the codesandbox example. 我用Google搜索的大多数答案都表明,
onClick
不会对通过return
键按下提交表单作出反应,但这并不是如在codesandbox示例中看到的那样。
When will they behave differently, apart from when dealing with DOM manipulation/event simulation? 除了处理DOM操作/事件模拟时,它们何时会表现不同?
Fundamentally, this is up to the browser. 从根本上说,这取决于浏览器。 Some browsers might call a submit button's
onClick
when the form is submitted by pressing the return key, but the standard doesn't mandate this. 某些浏览器可能会在按回车键提交表单时调用提交按钮的
onClick
,但标准并未强制要求。 Others might only call onClick
when return is pressed if the submit button is selected . 如果选择了提交按钮,其他人可能只在按下返回时调用
onClick
。 Others might not fire it unless the button is manually clicked. 除非手动点击按钮,否则其他人可能不会触发它。
If you want the best portability, use onSubmit
for what it's designed for: to detect form submission. 如果您想要最佳的可移植性,请使用
onSubmit
来实现它的设计目的:检测表单提交。
The other main difference is the target for the event. 另一个主要区别是事件的目标。
Note that the submit event fires on the <form> element itself, and not on any <button> or <input type="submit"> inside it. (Forms are submitted, not buttons.)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.