简体   繁体   中英

How to focus on a Material UI Button while Enter key pressing

after the last inputing finished, user want to press save button

'Tab' key will move the focus to the next element(button), I want use 'Enter' key realize this, but i did not how to do that?

You need to use ref to focus the button when press Enter in the last input:

Firest, create ref:

const buttonRef = useRef(null);

Then, add ref in the button:

<button ref={buttonRef} ...>

After that, add onKeyPress in the last input to check press Enter :

<input onKeyPress={handleKeyPress} ...>

Anh this is the handleKeyPress :

  const handleKeyPress= e => {
    if(e.key === "Enter"){
      buttonRef.current.focus()
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM