How to submit a form using Enter key in react.js?

前端 未结 6 435
野的像风
野的像风 2020-12-04 10:34

Here is my form and the onClick method. I would like to execute this method when the Enter button of keyboard is pressed. How ?

N.B: No jquery is appreciated.

6条回答
  •  孤城傲影
    2020-12-04 11:17

    import React , {useEffect , useRef } from 'react' ; 
    
    function Example() {
    
     let inp = useRef() 
     useEffect(()=>{ 
       if (!inp && !inp.current) return 
       inp.current.focus() ; 
       return () => inp = null ;  
     });
     
     const handleSubmit = () => { 
        //...  
     }
    
     return ( 
        
    { e.preventDefault(); handleSubmit(e); }} >
    ) }

    enter code heresometimes in popus it would not work to binding just a form and passing the onSubmit to the form because form may not have any input . in this cases if you bind the event to the document by doing document.addEventListener it will be cause problem in another parts of the application on count of this for solving thiis issue we should wrapp a form and should put a input with that is hidden by css .. then you foucus on that input by ref it will be work currectly .

提交回复
热议问题