React onKeyDown/onKeyUp events on non-input elements

試著忘記壹切 提交于 2020-12-05 10:28:07

问题


I need to capture cmd button up and down events, in order to choose, whether to use concatenation or not in setState. How do i get these events, for example, on table element?


回答1:


You have to capture the keypress then in body/window level. Table element doesn't have input focus so you can't capture the keys from table (without input element).

var cmdDown = false;

document.body.addEventListener('keydown', function(event) {
  var key = event.keyCode || event.charCode || 0;
  if ([91,93,224,17].indexOf(key) !== -1) {
    cmdDown = true;
  }
  console.log('CMD DOWN: ' + cmdDown.toString());    
});

document.body.addEventListener('keyup', function(event) {
  var key = event.keyCode || event.charCode || 0;
  if ([91,93,224,17].indexOf(key) !== -1) {
    cmdDown = false;
  }
  console.log('CMD DOWN: ' + cmdDown.toString());
});


来源:https://stackoverflow.com/questions/39135912/react-onkeydown-onkeyup-events-on-non-input-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!