java扫码枪键盘_浅谈在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 ===

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在React实现图形验证码,可以使用第三方库react-captcha来生成验证码。首先,需要在项目安装react-captcha。 ``` npm install react-captcha --save ``` 然后,在组件使用Captcha组件来生成验证码。在这个组件,我们可以设置一些属性,例如验证码长度、字符集、背景颜色等等。在这个例子,我们将生成一个长度为6的验证码,字符集为大小写字母和数字,背景颜色为浅灰色。 ``` import React from 'react'; import Captcha from 'react-captcha'; class CaptchaExample extends React.Component { render() { return ( <Captcha captchaCodeLength={6} captchaChars={'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'} captchaBgColor={'#f2f2f2'} /> ); } } export default CaptchaExample; ``` 此时,我们已经能够在React生成图形验证码了。但是,我们还需要在验证码输入验证用户输入是否正确。这可以通过在Captcha组件上设置onVerify属性来实现。 ``` import React from 'react'; import Captcha from 'react-captcha'; class CaptchaExample extends React.Component { constructor(props) { super(props); this.state = { captchaCode: '', validCaptcha: '' }; } handleVerify = code => { this.setState({ validCaptcha: code }); }; handleSubmit = e => { e.preventDefault(); if (this.state.captchaCode === this.state.validCaptcha) { alert('验证码正确!'); } else { alert('验证码错误!'); } }; handleChange = e => { this.setState({ captchaCode: e.target.value }); }; render() { return ( <form onSubmit={this.handleSubmit}> <Captcha captchaCodeLength={6} captchaChars={'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'} captchaBgColor={'#f2f2f2'} onVerify={this.handleVerify} /> <input type="text" value={this.state.captchaCode} onChange={this.handleChange} /> <button type="submit">提交</button> </form> ); } } export default CaptchaExample; ``` 在这个例子,我们在Captcha组件上设置了onVerify属性,当用户输入验证码时,会自动调用handleVerify方法,将生成的验证码存储在validCaptcha状态。当用户提交表单时,将会比较用户输入的验证码和生成的验证码是否一致。如果一致,则弹出“验证码正确!”的提示框,否则弹出“验证码错误!”的提示框。 这样,我们就完成了在React生成图形验证码的过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值