我需要一個表單內的按鈕,onSubmit當用戶按下 Enter 按鈕時觸發事件。
這是作業解決方案的示例:
<form onSubmit={() => console.log('ok')}>
<button type="submit" autoFocus>Submit</button>
</form>
當用戶按下 Enter 時,會onSubmit被正確觸發。
我的問題是當我必須在組件的渲染道具中渲染這個按鈕時:
<Component render={()=> (
<button type="submit" autoFocus /> // here the button will not be focused
)}/>
所以當我按下 Enter 鍵時,什么也沒有發生。
有什么方法可以僅使用 html 屬性獲得有效的解決方案嗎?
uj5u.com熱心網友回復:
它不起作用,因為在您的示例中,按鈕onClick事件未連接到GoogleLogin或 wrapping Component。
一步步:
由于autoFocus,當您的按鈕呈現時,它會自動聚焦。只要您enter在它仍然處于焦點時單擊,就會觸發該按鈕的單擊事件。
在純html示例onSubmit中,表單的 被觸發,因為按鈕有一個type="submit".
<form onSubmit={() => console.log('ok')}>
<button type="submit" autoFocus>Submit</button>
</form>
因此,如果您希望示例觸發GoogleLogin點擊enter,則必須通過點擊按鈕手動觸發它,如下所示:
<GoogleLogin
render={(renderProps) => (!renderProps.disabled ?
<button autoFocus onClick={renderProps.onClick}>
This is my custom Google button
</button>: null
)}
/>
請記住,如果用戶單擊 Tab,自動對焦將丟失并且enter輸入將不再觸發onClick事件。
相反,您可以設定一個事件偵聽器,該偵聽器將偵聽enter輸入并在呈現時觸發 GoogleLogin,獨立于 autoFocus。或者您讓您的用戶單擊該按鈕而不是輸入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383862.html
標籤:javascript 反应 形式 提交时
