【发布时间】:2018-02-26 15:47:15
【问题描述】:
在使用像 React 这样的框架时直接访问文档对象是不好的做法。
我正在使用外部条形码扫描仪,我想检测何时扫描数字并填充特定字段。我想避免跟踪焦点所在的字段。
这是我的代码
render(){
....
document.onkeypress = (e) => {
e = e || window.event;
const digit = e.key;
if(e.target.nodeName === 'BODY' && digit.match(/[0-9]/i)){
console.log(digit);
}
};
【问题讨论】:
-
我个人不建议在使用像 React 或 Vue 等 SPA 时向文档或窗口添加事件侦听器......也就是说 - React 文档确实提供了一些信息 - 也许你在哪里放置你的听众'是一个更重要的问题,而不是你的
render方法等react-cn.github.io/react/tips/dom-event-listeners.html -
我感觉到X/Y problem here。为什么你的组件中需要
document上的keypress处理程序?
标签: javascript reactjs barcode-scanner