问题
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