淺談在react中如何實現(xiàn)掃碼槍輸入
觸發(fā)原理
原理就是監(jiān)聽鍵盤輸入,比如掃一個為6970596130126的69條形碼,用掃碼槍掃一下會在光標位置依次輸出:
6
9
7
0
5
9
6
1
3
0
2
6
但這不是完整的,所以需要寫一個函數(shù)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階段移除監(jiān)聽器時,需要傳遞函數(shù)名,否則無法移除!!這是非常值得注意的一點。
完整使用
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...
});
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
react-router-dom入門使用教程(路由的模糊匹配與嚴格匹配)
這篇文章主要介紹了react-router-dom入門使用教程,主要介紹路由的模糊匹配與嚴格匹配,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08
react antd如何防止一份數(shù)據(jù)多次提交
這篇文章主要介紹了react antd如何防止一份數(shù)據(jù)多次提交問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
React?Native?加載H5頁面的實現(xiàn)方法
這篇文章主要介紹了React?Native?加載H5頁面的實現(xiàn)方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04
React實現(xiàn)監(jiān)聽粘貼事件并獲取粘貼板中的截圖
這篇文章主要介紹了React實現(xiàn)監(jiān)聽粘貼事件并獲取粘貼板中的截圖方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
React Native中實現(xiàn)動態(tài)導(dǎo)入的示例代碼
隨著業(yè)務(wù)的發(fā)展,每一個 React Native 應(yīng)用的代碼數(shù)量都在不斷增加。作為一個前端想到的方案自然就是動態(tài)導(dǎo)入(Dynamic import)了,本文介紹了React Native中實現(xiàn)動態(tài)導(dǎo)入的示例代碼,需要的可以參考一下2022-06-06

