体育彩票飞鱼开奖结果:浅谈在react中如何实现扫码枪输入
江西多乐彩11选5走势图 www.ptdvv.cn 转载 更新时间:2018年07月04日 10:48:03 作者:张君卓 我要评论
这篇文章主要介绍了浅谈在react中如何实现扫码枪输入,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
触发原理
原理就是监听键盘输入,比如扫一个为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... }); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章
郁闷!ionic中获取ng-model绑定的值为undefined如何解决
很是郁闷!ionic中获取ng-model绑定的值为undefined,如何解决?2016-08-08BootStrap模态框和select2合用时input无法获取焦点的解决方法
在bootstrap的模态框里使用select2插件,会导致select2里的input输入框没有办法获得焦点,没有办法输入。怎么解决这个问题呢?下面小编给大家带来了BootStrap模态框和select2合用时input无法获取焦点的解决方法,一起看看吧2017-09-09通过复制Table生成word和excel的javascript代码
通过复制Table生成word和excel,个人感觉这个功能还是比较实用的,下面有个不错的示例,希望对大家有所帮助2014-01-01
最新评论