简体   繁体   English

检测何时使用onKeyPress而不是onKeyUp在React.js中按下Delete或Backspace键

[英]Detect when Delete or Backspace keys are pressed with onKeyPress and not with onKeyUp in React.js

I need to activate a function when the Delete or Backspace keys are pressed. 按下Delete或Backspace键时,我需要激活一个功能。 The call is made inside a number input filed which is part of a form. 呼叫是在作为表单一部分的数字输入字段中进行的。 This works: 这有效:

onKeyUp={((e) => this.onCero(e))}

This does not work: 这不起作用:

onKeyDown ={((e) => this.onCero(e))}

The function I am calling: 我正在调用的函数:

onCero = (e) => {
    e.preventDefault();
    if (e.key === "Delete" || e.key === "Backspace") {
        alert(e.key);
    }
};

I need to trigger the function when the key is pressed, not when it is released using React or JavaScript. 我需要在按下键时触发函数,而不是在使用React或JavaScript释放键时触发该函数。

Any ideas guys? 有想法吗? Thanks. 谢谢。

You can use the classic JavaScript's event listeners for that. 您可以使用经典的JavaScript事件监听器。

It would be something like this: 就像这样:

componentDidMount() {
  document.addEventListener('keydown', this.onCero, false);
}

componentWillUnmount() {
  document.removeEventListener('keydown', this.onCero, false);
}

And then use can use the key codes in your onCero function: 然后使用可以使用onCero函数中的键代码:

onCero = (e) => {
  if (e.keyCode === 27 || e.keyCode === 13) {
    alert(e.keyCode);
  }
};

Your code seems to be working fine. 您的代码似乎运行正常。

 class App extends React.Component{ constructor(props){ super(props); } onCero = (e) => { console.log(e.key); e.preventDefault(); if (e.key === "Delete" || e.key === "Backspace") { alert(e.key); } }; render(){ return( <input type="number" onKeyDown ={((e) => this.onCero(e))} /> ) } } ReactDOM.render( <App/>, document.getElementById("root") ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

You can call it via onKeyPress={this.onCero}. 您可以通过onKeyPress = {this.onCero}进行调用。 This should work 这应该工作

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

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