猿问

类型错误:无法读取未定义的 Scanner.js 属性“扫描”

我正在尝试集成scanner-js到我的反应应用程序中,但收到错误TypeError: Cannot read property 'scan' of undefined

您可以找到以下代码:


慕尼黑的夜晚无繁华
浏览 140回答 2
2回答

MM们

import { scanner } from 'scanner-js';class Home extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {};&nbsp; }&nbsp; scan = () => {&nbsp; &nbsp; scanner.scan(this.displayImagesOnPage, {&nbsp; &nbsp; &nbsp; output_settings: [&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'return-base64',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; format: 'jpg',&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; });&nbsp; };&nbsp; displayImagesOnPage(successful, mesg, response) {&nbsp; &nbsp; if (!successful) {&nbsp; &nbsp; &nbsp; // On error&nbsp; &nbsp; &nbsp; console.error('Failed: ' + mesg);&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; if (&nbsp; &nbsp; &nbsp; successful &&&nbsp; &nbsp; &nbsp; mesg != null &&&nbsp; &nbsp; &nbsp; mesg.toLowerCase().indexOf('user cancel') >= 0&nbsp; &nbsp; ) {&nbsp; &nbsp; &nbsp; // User cancelled.&nbsp; &nbsp; &nbsp; console.info('User cancelled');&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; var scannedImages = scanner.getScannedImages(response, true, false); // returns an array of ScannedImage&nbsp; &nbsp; for (&nbsp; &nbsp; &nbsp; var i = 0;&nbsp; &nbsp; &nbsp; scannedImages instanceof Array && i < scannedImages.length;&nbsp; &nbsp; &nbsp; i++&nbsp; &nbsp; ) {&nbsp; &nbsp; &nbsp; var scannedImage = scannedImages[i];&nbsp; &nbsp; &nbsp; var elementImg = scanner.createDomElementFromModel({&nbsp; &nbsp; &nbsp; &nbsp; name: 'img',&nbsp; &nbsp; &nbsp; &nbsp; attributes: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; class: 'scanned',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; src: scannedImage.src,&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <button type="button" onClick={this.scan}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Scan&nbsp; &nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}export default Home;当我将鼠标悬停在该scanner对象上时,会显示以下内容,但我不知道为什么它会抛出未定义的错误。有人可以帮我找到问题吗?

湖上湖

这是因为你导入错了。如果您在 npm 上检查包,您可以看到没有导出的模块,因此您无法导入单个导出(import {scanner} from 'scanner-js'),也无法导入默认导出(import scanner from 'scanner-js)。您只需导入整个模块即可产生副作用,并且它将scanner向window对象添加一个全局变量。import 'scanner-js';console.log(typeof scanner);// => objectconsole.log(typeof scanner.scan);// => function如果您使用 ESLint,则需要添加scanner为全局变量。CodeSandbox链接:https://codesandbox.io/s/scanner-js-hcz2j
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答