最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React <input>: Dismiss soft keyboard on enter - Stack Overflow

programmeradmin1浏览0评论

I'm writing a React app that will be used on mobile devices.

One of the pages has an <input> text that the user inputs with the keyboard. Entering text in the field has an immediate effect, and thus no button needs to be pushed afterwards. I'd like to have the soft keyboard 'enter' key simply dismiss the keyboard without taking any action. Is this at all possible? It sounds so simple, yet I couldn't find how to do it.

For what it's worth, I tried adding enterKeyHint="done" attribute (as described here), but other than changing the enter title from 'done' to a 'v' sign it does not dismiss the keyboard.

Any ideas? Thanks in advance!

I'm writing a React app that will be used on mobile devices.

One of the pages has an <input> text that the user inputs with the keyboard. Entering text in the field has an immediate effect, and thus no button needs to be pushed afterwards. I'd like to have the soft keyboard 'enter' key simply dismiss the keyboard without taking any action. Is this at all possible? It sounds so simple, yet I couldn't find how to do it.

For what it's worth, I tried adding enterKeyHint="done" attribute (as described here), but other than changing the enter title from 'done' to a 'v' sign it does not dismiss the keyboard.

Any ideas? Thanks in advance!

Share Improve this question asked Apr 30, 2021 at 3:48 chakazchakaz 3113 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Sounds like it's simply a matter of triggering blur() from the element itself. You could either trigger blur() from the event handler or by using useRef.

Make sure to e.stopPropagation() or e.preventDefault() if you don't want your input to bubble the event upwards, or if it's inside of a form

export default function App() {
  const onEnter = (e) => {
    if (e.key === "Enter") {
      e.target.blur();
    }
  };

  return (
    <div className="App">
      <input onKeyUp={onEnter} />
    </div>
  );
}

Demo: https://codesandbox.io/s/relaxed-antonelli-j6c5d?file=/src/App.js

发布评论

评论列表(0)

  1. 暂无评论