图像不适用于React Native + TypeScript + Expo

时间:2018-09-20 22:07:21

标签: typescript react-native expo

我正在使用Typescript构建CRNA,但似乎无法正确解析图像。我没有遵循这里的文档:https://facebook.github.io/react-native/docs/images

这是在同时构建IOS和Android模拟器时遇到的错误:

Unable to resolve ./img.png" from ".//build/components/PlateCounter.js`: The module `./img.png` could not be found"
Failed building JavaScript bundle

图像在编译后没有与我的.js文件一起显示在/ build文件夹中,因此我想这会导致Expo构建失败,但是我不知道如何将图像编译为/build Build folder screenshot/

以下是我要在其中渲染图像的组件:

import React from 'react';
import { View, Image } from 'react-native';

export default class PlateCounter extends React.Component<any, any> {

  public render() {
    return (
      <View>
        <Image source={require('./img.png')} />
      </View>
   );
  }
}

这是该文件夹的文件结构:Screenshot

正如您在图像中看到的那样,我尝试添加@ 2x和@ 3x变体,但这没有任何改变。

我的package.json:

{
  "name": "TestRN",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "@types/react": "^16.4.14",
    "@types/react-dom": "^16.0.7",
    "@types/react-native": "^0.56.21",
    "@types/react-navigation": "^2.0.21",
    "concurrently": "^4.0.1",
    "react-native-scripts": "1.14.0",
    "react-test-renderer": "16.3.1",
    "rimraf": "^2.6.2",
    "tslint": "^5.11.0",
    "typescript": "^3.0.3"
  },
  "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "lint": "tslint src/**/*.ts",
    "tsc": "tsc",
    "clean": "rimraf build",
    "build": "yarn run clean && yarn run tsc --",
    "watch": "yarn run build -- -w",
    "watchAndRunAndroid": "concurrently \"yarn run watch\" \"yarn run android\"",
    "buildRunAndroid": "yarn run build && yarn run watchAndRunAndroid ",
    "watchAndRunIOS": "concurrently \"yarn run watch\" \"yarn run ios\"",
    "buildRunIOS": "yarn run build && yarn run watchAndRunIOS ",
    "watchAndStart": "concurrently \"yarn run watch\" \"yarn run start\"",
    "buildAndStart": "yarn run build && yarn run watchAndStart ",
    "start": "react-native-scripts start",
    "eject": "react-native-scripts eject",
    "android": "react-native-scripts android",
    "ios": "react-native-scripts ios",
    "debug": "REACT_DEBUGGER=\"unset ELECTRON_RUN_AS_NODE\" && open -g 'rndebugger://set-debugger-loc?port=19001'"
  },
  "dependencies": {
    "@expo/vector-icons": "^6.3.1",
    "expo": "^27.0.1",
    "native-base": "^2.8.0",
    "react": "16.3.1",
    "react-native": "~0.55.2",
    "react-navigation": "^2.14.2",
    "unstated": "^2.1.1",
    "watchman": "^1.0.0"
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码,请确保您的文件具有适当的权限。

import React from 'react';
import { View, Image } from 'react-native';

export default class PlateCounter extends React.Component<any, any> {

  public render() {
    let imgSource = require('./img.png');
    return (
      <View>
        <Image source={imgSource} />
      </View>
   );
  }
}