我是 Javascript 新手,我正在尝试使用 React Native 编写一个应用程序来接受来自外部 RFID 设备的键盘输入。通过使用 react-native-keyevent 我们可以捕获来自 RFID 设备的输入,react-native keyevent 捕获的键码似乎与我刚刚通过 Google 找到的 ascii 码表不同,但是 hex_to_ascii 仍然可以解释这些字符,而结果是嵌入了奇怪的字符,不知道是哪一步导致了问题?以下是代码:
import QRCodeScanner from 'react-native-qrcode-scanner';
import KeyEvent from 'react-native-keyevent';
const HomeScreen = (props) => {
...
const hex_to_ascii = (str) => {
var hex = str.toString();
let strFinal = '';
for (var n = 0; n < hex.length; n += 2) {
strFinal += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
return strFinal;
};
...
useEffect( () => {
if (isSwEnabled) {
console.log('addListener');
let charArray = [];
let currEPC = '';
let currHex = '';
KeyEvent.onKeyUpListener((keyEvent) => {
if (keyEvent.pressedKey === '/') {
console.log(charArray);
charArray.forEach((value, index, array) => {
currHex = currHex.concat(value);
});
console.log(charArray.join().replace(/,/g, '').substr(8));
const aa = hex_to_ascii(currHex);
const bb = 'PB01G4E9';
console.log(aa === bb); // output: false
console.log(aa.length); // output: 13
console.log(bb.length); // output: 8
charArray = [];
console.log(`cardEPC: ${aa}`);
// below code for test/compare
const array = [50, 42, 30, 31, 47, 34, 45, 39];
const a = hex_to_ascii(array.join().replace(/,/g, ''));
// const a = hex_to_ascii('5042303147344539');
const b = 'PB01G4E9';
console.log(a); // output: PB01G4E9
console.log(a === b); // output: true
} else if (keyEvent.pressedKey.trim() !== '') {
charArray.push(keyEvent.pressedKey.trim());
}
});
} else {
KeyEvent.removeKeyUpListener();
console.log('removeListener');
}
},
[dispatch, isSwEnabled]
}
);
return ( ... );
}