简体   繁体   English

ReferenceError 找不到变量:Image - React Native,create-expo-app。 无法使用 Image() 创建 HTMLImageElement

[英]ReferenceError Can't find variable: Image - React Native, create-expo-app. Can't create an HTMLImageElement with Image()

The Error错误

I'm early in learning to use React-Native, working with create-expo-app.我很早就开始学习使用 React-Native,使用 create-expo-app。

When I run npm start, I run into an error giving this output:当我运行 npm start 时,我遇到了一个错误,给出了这个 output:

ERROR ReferenceError: Can't find variable: Image错误 ReferenceError:找不到变量:图片

I expect that the second two errors are caused by the first error.我希望后两个错误是由第一个错误引起的。

ERROR Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication().错误不变违规:无法调用 JavaScript 模块方法 AppRegistry.runApplication()。 Module has not been registered as callable.模块尚未注册为可调用。 Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.已注册的可调用模块 JavaScript (n = 11):Systrace、JSTimers、HeapCapture、SamplingProfiler、RCTLog、RCTDeviceEventEmitter、RCTNativeAppEventEmitter、GlobalPerformanceLogger、JSDevSupportModule、HMRClient、RCTEventEmitter。 A frequent cause of the error is that the application entry file path is incorrect.错误的一个常见原因是应用程序入口文件路径不正确。 This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.当 JS 包损坏或加载 React Native 时出现早期初始化错误时,也会发生这种情况。

ERROR Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication().错误不变违规:无法调用 JavaScript 模块方法 AppRegistry.runApplication()。 Module has not been registered as callable.模块尚未注册为可调用。 Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.已注册的可调用模块 JavaScript (n = 11):Systrace、JSTimers、HeapCapture、SamplingProfiler、RCTLog、RCTDeviceEventEmitter、RCTNativeAppEventEmitter、GlobalPerformanceLogger、JSDevSupportModule、HMRClient、RCTEventEmitter。 A frequent cause of the error is that the application entry file path is incorrect.错误的一个常见原因是应用程序入口文件路径不正确。 This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.当 JS 包损坏或加载 React Native 时出现早期初始化错误时,也会发生这种情况。

My Project I've built a minimal app that causes the error.我的项目我构建了一个导致错误的最小应用程序。

I ran:我跑了:

npx create-expo-app TestImage
cd TestImage
npm install --save --legacy-peer-deps react-canvas-map

(react-canvas-map: https://www.npmjs.com/package/react-canvas-map ) (反应画布地图: https://www.npmjs.com/package/react-canvas-map

App.js应用程序.js

The error originates from line 7: "new Image();"错误源自第 7 行:“new Image();”

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';

import React, { useState } from 'react'
import { Map, Marker } from 'react-canvas-map'

const markerOneImage = new Image();
markerOneImage.src = './static/marker-blue.svg';

export default function App() {
    const [markerOneCoords, setMarkerOneCoords] = useState({ x: 100, y: 200 })

    return (
        <View style={styles.container}>
            <Text>Open up App.js to start working on your app!</Text>
            <StatusBar style="auto" />
            <div style={{ height: '50vh', border: '1px solid #ddd', marginTop: '1rem' }}>
                <Map
                    image={"./static/map.jpg"}
                >
                    <Marker
                        image={markerOneImage}

                        markerKey={"marker-one"}
                        coords={markerOneCoords}
                        onDragTick={setMarkerOneCoords}
                        onDragEnd={setMarkerOneCoords}
                        onClick={() => {
                            alert('You clicked marker one!')
                        }}
                    />
                </Map>
            </div>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
});

The error occurs when I run运行时出现错误

npm start

(which calls expo start ) (调用expo start

The entirety of my code either comes as the standard create-expo-app boilerplate code, or from a demonstrably working example: https://bor3ham.github.io/react-canvas-map/ (an example project on the react-canvas-map library).我的全部代码要么来自标准的 create-expo-app 样板代码,要么来自一个可证明有效的示例: https://bor3ham.github.io/react-canvas-map/ (react-canvas 上的示例项目-地图库)。

Some Explanation一些解释

Image() is a HTML Standard element: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image Image() 是一个 HTML 标准元素: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image

It is equivalent to "document.getElement("img"). If I try that, I get the same error, for 'document'.它等同于“document.getElement("img")”。如果我尝试这样做,对于“document”我会得到同样的错误。

ERROR ReferenceError: Can't find variable: document错误 ReferenceError:找不到变量:文档

System Details系统详情

npm --version
8.19.3

package.json: package.json:

{
  "name": "testimage",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "expo": "~47.0.6",
    "expo-status-bar": "~1.4.2",
    "react": "18.1.0",
    "react-canvas-map": "^0.1.8",
    "react-native": "0.70.5"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}

Have I set up my project incorrectly?我是否错误地设置了我的项目?

Am I missing an import that allows me to use HTMLImageElements from the HTML Standard Specification ( https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement )?我是否缺少允许我使用 HTML 标准规范 ( https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement ) 中的 HTMLImageElements 的导入?

Does React 18.1.0 (my version) require me to do something differently from the tutorial (running on 16.14.0) in relation to using "Image()"?关于使用“Image()”,React 18.1.0(我的版本)是否要求我做一些与教程(在 16.14.0 上运行)不同的事情? I've tried setting react in package.json to 16.14.0, then re-running npm install and npm start (to match what I saw in the demo - https://bor3ham.github.io/react-canvas-map/ ).我试过将 package.json 中的 react 设置为 16.14.0,然后重新运行 npm 安装和 npm 启动(以匹配我在演示中看到的内容 - https://bor3ham.88166911485 )。 The same error occurs, though it notes:发生相同的错误,但它指出:

Some dependencies are incompatible with the installed expo version:
  react@16.14.0 - expected version: 18.1.0
Your project may not work correctly until you install the correct versions of the packages.
Install individual packages by running npx expo install react@18.1.0

I didn't expect this problem to last as long as it has done.我没想到这个问题会持续这么久。 I haven't found any sources talking about this as an issue, but I may have missed them as I don't have a good grasp of what terms to use to search here.我没有找到任何消息来源谈论这个问题,但我可能错过了它们,因为我不太了解使用什么术语来搜索这里。

I've worked this out now.我现在已经解决了。

My question was effectively a duplicate of: Exception: Can't find variable: document我的问题实际上是以下内容的重复: Exception: Can't find variable: document

Quoting an explanative answer from that question: https://stackoverflow.com/a/66003682/20535652引用该问题的解释性答案: https://stackoverflow.com/a/66003682/20535652

Unfortunately, both window and document are part of the web standard, not JavaScript (ECMA standard).不幸的是,window 和文档都是 web 标准的一部分,而不是 JavaScript(ECMA 标准)。

React Native uses JS to control rendering, but lack of DOM-manipuling itself, so you can not use many web-based APIs directly in React Native. React Native 使用 JS 来控制渲染,但本身缺乏 DOM 操作,因此您不能直接在 React Native 中使用许多基于 Web 的 API。

And that answer poses two possible options for resolution:这个答案提出了两种可能的解决方案:

Using WebView in React Native app to load your web app在 React Native 应用程序中使用 WebView 加载您的 web 应用程序

Try controling the React Native component yourself, rewrite logic尝试自己控制 React Native 组件,重写逻辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM