react addEventListener监听键盘事件实现扫码枪输入(转)
程序员文章站
2022-06-14 22:27:38
...
转载链接 https://blog.csdn.net/wjy199506/article/details/78885289
componentDidMount() {
var code = "";
var lastTime,nextTime;
var lastCode,nextCode;
window.addEventListener('keypress',function(e){
nextCode = e.which;
nextTime = new Date().getTime();
if(lastCode != null && lastTime != null && nextTime - lastTime <= 30) {
code += String.fromCharCode(lastCode);
} else if(lastCode != null && lastTime != null && nextTime - lastTime > 100){
code = "";
}
lastCode = nextCode;
lastTime = nextTime;
if(e.which == 13){
console.log(code);
code = "";
}
})
}