简体   繁体   English

反应<input> : 回车时关闭软键盘

[英]React <input>: Dismiss soft keyboard on enter

I'm writing a React app that will be used on mobile devices.我正在编写一个将在移动设备上使用的 React 应用程序。

One of the pages has an <input> text that the user inputs with the keyboard.其中一个页面具有用户使用键盘输入的<input>文本。 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.对于它的价值,我尝试添加enterKeyHint="done"属性(如此所述),但除了将输入标题从“完成”更改为“v”符号之外,它不会关闭键盘。

Any ideas?有任何想法吗? Thanks in advance!提前致谢!

Sounds like it's simply a matter of triggering blur() from the element itself.听起来这只是从元素本身触发blur()的问题。 You could either trigger blur() from the event handler or by using useRef .您可以从事件处理程序或使用useRef触发blur()

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如果您不希望输入使事件向上冒泡,或者如果它位于表单内部,请确保使用e.stopPropagation()e.preventDefault()

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

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

CodeSandbox: https://codesandbox.io/s/relaxed-antonelli-j6c5d?file=/src/App.js代码沙盒: https://codesandbox.io/s/relaxed-antonelli-j6c5d?file=/src/App.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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