[英]Why does react form's onSubmit fire after every keystroke, how to use enter button to submit form?
[英]Form onSubmit={handleSubmit} is triggered through any button which has type=“submit” or not specified or after enter on textbox
我正在嘗試獲取<form onClick={handleSubmit} />
的提交者/調用者 在事件 arg 我想檢查調用者按鈕的“id”,例如<button id="submitter">Submit with id</button>
和僅當 'id' 匹配時才允許繼續。
我嘗試過 Formik、Final-Form、Redux 形式以及獨立的<form>
標簽。 即使在輸入標簽上按 enter 也會觸發提交表單。 我知道這是默認行為,但我需要限制允許哪個調用者繼續。
我必須使用標簽<form>
否則滾動到最近的錯誤之類的東西不起作用。 嘗試使用最終 Forms。
在我的應用程序中,我有很多用於將字段添加到數組刪除的按鈕,但並非所有按鈕都有 type="button" 可以防止這種情況發生。 但正如我所說,即使在文本框上輸入也會觸發這個 onSubmit 所以我必須找到更好的解決方案。
請記住,我無法避免使用<form>
標簽。 謝謝
https://codesandbox.io/s/dazzling-jackson-2m4r5
<form
onSubmit={e => {
e.persist();
e.preventDefault();
// HOW TO GET id="my-submit-button" HERE ???
console.log(e);
if(id==='my-submit-button') handleSubmit()
}}
>
<input type="text" name="firstName" />
<button>Button without type</button>
<button type="button">Button type=button</button>
<button type="submit">Button type=submit</button>
<button id="my-submit-button">Button with id</button>
</form>
您可以使用點擊事件:
<form onSubmit={e => e.preventDefault()}>
<input type="text" name="firstName" />
<button>Button without type</button>
<button type="button">Button type=button</button>
<button type="submit">Button type=submit</button>
<button id="my-submit-button" onClick={() => {
console.log("Button click");
// handleSubmit()
}}>Button with id</button>
</form>
正如@epascarello 提到的那樣,這有效-> document.activeElement
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.