幽灵资源网 Design By www.bzswh.com
触发原理
原理就是监听键盘输入,比如扫一个为6970596130126的69条形码,用扫码枪扫一下会在光标位置依次输出:
6
9
7
0
5
9
6
1
3
0
2
6
但这不是完整的,所以需要写一个函数scanEvent来整理收集到的每个编号。
let code = '';
let lastTime,
nextTime,
lastCode,
nextCode;
function scanEvent(e, cb) {
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) {
cb(code);
console.log('code', code);
code = '';
}
}
export { scanEvent };
react中的坑
当我们想在willComponentUnMount阶段移除监听器时,需要传递函数名,否则无法移除!!这是非常值得注意的一点。
完整使用
class Sample extends React.Component{
componentDidMount(){
window.addEventListener('keypress', this.scanWrapper, false);
}
componentWillUnmount() {
window.removeEventListener('keypress', this.scanWrapper, false);
}
scanWrapper(e) {
scanEvent(e, (code) => {
// to do something...
});
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
幽灵资源网 Design By www.bzswh.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
幽灵资源网 Design By www.bzswh.com
暂无评论...