简体   繁体   English

如何处理 ReactJS 中的 `onKeyPress` 事件?

[英]How to handle the `onKeyPress` event in ReactJS?

How can I make the onKeyPress event work in ReactJS?如何让onKeyPress事件在 ReactJS 中工作? It should alert when enter (keyCode=13) is pressed.按下enter (keyCode=13)时,它应该enter (keyCode=13)警报。

var Test = React.createClass({
    add: function(event){
        if(event.keyCode == 13){
            alert('Adding....');
        }
    },
    render: function(){
        return(
            <div>
                <input type="text" id="one" onKeyPress={this.add} />    
            </div>
        );
    }
});

React.render(<Test />, document.body);

I am working with React 0.14.7, use onKeyPress and event.key works well.我正在使用 React 0.14.7,使用onKeyPressevent.key效果很好。

handleKeyPress = (event) => {
  if(event.key === 'Enter'){
    console.log('enter press here! ')
  }
}
render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyPress={this.handleKeyPress} />
        </div>
     );
}

For me onKeyPress the e.keyCode is always 0 , but e.charCode has correct value.对我来说onKeyPress e.keyCode总是0 ,但e.charCode有正确的值。 If used onKeyDown the correct code in e.charCode .如果在e.charCode使用onKeyDown正确的代码。

var Title = React.createClass({
    handleTest: function(e) {
      if (e.charCode == 13) {
        alert('Enter... (KeyPress, use charCode)');
      }
      if (e.keyCode == 13) {
        alert('Enter... (KeyDown, use keyCode)');
      }
    },
    render: function() {
      return(
        <div>
          <textarea onKeyPress={this.handleTest} />
        </div>
      );
    }
  });

React Keyboard Events . 反应键盘事件

render: function(){
     return(
         <div>
           <input type="text" id="one" onKeyDown={this.add} />
        </div>
     );
}

onKeyDown detects keyCode events. onKeyDown检测keyCode事件。

Keypress event is deprecated, You should use Keydown event instead. Keypress 事件已弃用,您应该改用 Keydown 事件。

https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event

handleKeyDown(event) {
    if(event.keyCode === 13) { 
        console.log('Enter key pressed')
  }
}

render() { 
    return <input type="text" onKeyDown={this.handleKeyDown} /> 
}

If you wanted to pass a dynamic param through to a function, inside a dynamic input::如果您想在动态输入中将动态参数传递给函数:

<Input 
  onKeyPress={(event) => {
    if (event.key === "Enter") {
      this.doSearch(data.searchParam)
    }
  }}
  placeholder={data.placeholderText} />
/>

Hope this helps someone.希望这可以帮助某人。 :) :)

var Test = React.createClass({
     add: function(event){
         if(event.key === 'Enter'){
            alert('Adding....');
         }
     },
     render: function(){
        return(
           <div>
            <input type="text" id="one" onKeyPress={(event) => this.add(event)}/>    
          </div>
        );
     }
});

React is not passing you the kind of events you might think. React 不会传递您可能认为的那种事件。 Rather, it is passing synthetic events .相反,它正在传递合成事件

In a brief test, event.keyCode == 0 is always true.在简短的测试中, event.keyCode == 0始终为真。 What you want is event.charCode你想要的是event.charCode

Late to the party, but I was trying to get this done in TypeScript and came up with this:聚会迟到了,但我试图在 TypeScript 中完成它并想出了这个:

<div onKeyPress={(e: KeyboardEvent<HTMLDivElement>) => console.log(e.key)}

This prints the exact key pressed to the screen.这会将按下的确切键打印到屏幕上。 So if you want to respond to all "a" presses when the div is in focus, you'd compare e.key to "a" - literally if(e.key === "a").因此,如果您想在 div 处于焦点时响应所有“a”按下,您可以将 e.key 与“a”进行比较——字面意思是 if(e.key === "a")。

There are some challenges when it comes to keypress event.在按键事件方面存在一些挑战。 Jan Wolter's article on key events is a bit old but explains well why key event detection can be hard. Jan Wolter 关于关键事件的文章有点旧,但很好地解释了为什么关键事件检测会很困难。

A few things to note:需要注意的几点:

  1. keyCode , which , charCode have different value/meaning in keypress from keyup and keydown. keyCode , which , charCode在 keypress 中与 keyup 和 keydown 具有不同的值/含义。 They are all deprecated, however supported in major browsers.它们都已弃用,但在主要浏览器中受支持。
  2. Operating system, physical keyboards, browsers(versions) could all have impact on key code/values.操作系统、物理键盘、浏览器(版本)都可能对键代码/值产生影响。
  3. key and code are the recent standard. keycode是最近的标准。 However, they are not well supported by browsers at the time of writing.但是,在撰写本文时,浏览器并没有很好地支持它们。

To tackle keyboard events in react apps, I implemented react-keyboard-event-handler .为了处理 React 应用程序中的键盘事件,我实现了react-keyboard-event-handler Please have a look.请看一看。

You need to call event.persist();你需要调用event.persist(); this method on your keyPress event.在您的 keyPress 事件上使用此方法。 Example:例子:

const MyComponent = (props) => {
   const keyboardEvents = (event) =>{
       event.persist();
       console.log(event.key); // this will return string of key name like 'Enter'
   }
   return(
         <div onKeyPress={keyboardEvents}></div>
   )
}

If you now type console.log(event) in keyboardEvents function you will get other attributes like:如果您现在在keyboardEvents函数中输入console.log(event) ,您将获得其他属性,例如:

keyCode // number
charCode // number
shiftKey // boolean
ctrlKey // boolean
altKey // boolean

And many other attributes以及许多其他属性

Thanks & Regards感谢和问候

PS: React Version : 16.13.1 PS:反应版本:16.13.1

This worked for me using hooks, by accessing the window element通过访问窗口元素,这对我使用钩子有用

useEffect(() => {
    window.addEventListener('keypress', e => {
      console.log(e.key)
    });
  }, []);

Keyboard Events In React With your generic knowledge of events in React so far, you can now implement keyboard events in React. React 中的键盘事件 到目前为止,您对 React 中的事件有了一般的了解,现在您可以在 React 中实现键盘事件。 As mentioned earlier, there are two keyboard events that can be used, the keyup and keydown events.如前所述,有两个键盘事件可以使用,keyup 和keydown 事件。

import React from 'react';

function Quiz(){
    handleAnswerChange(event){
        if(event.key === 'y'){
            alert('The sky is your starting point!')
    }
        else if (event.key === 'n') {
            alert('The sky is your limit👀')
    }
}

    return (
        <div>
                <p> Are You Smart?</p>
                    <input type="text" value={answer} onKeyPress={handleAnswerChange}/>
                <small> Press Y for Yes or N for No</small>
    </div>
)
}

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

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