在 Android 和 iOS 的 React Native 中存储图像的位置?

问题描述:

我是 React Native 的新手,想在 Android 和 iOS 中构建一个小型测试应用.

I'm new to react native and want to build a small test app in Android and iOS.

我在 index.ios.js 和 index.android.js 文件旁边创建了一个图像目录.

I have created an images directory alongside my index.ios.js and index.android.js files.

我下面的代码产生一个红屏错误,提示无法解析模块 ./images/tree.png...无效目录...":

My code below produces a red screen error saying "unable to resolve module ./images/tree.png... Invalid directory...":

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
} = React;

var TestApp = React.createClass({

  render: function() {

    return (
      <View>
        <Text>test app</Text>
        <Image 
          style={styles.thumbnail}
          source={require('./images/tree.png')} /> />
      </View>
    );
  },
});

var styles = StyleSheet.create({
  thumbnail: {
    width: 100,
    height: 100,
  },
});

AppRegistry.registerComponent('TestApp', () => TestApp);

我应该在哪里放置我的图片以及我应该如何引用它们?

Where should I place my images and how should I reference them?

假设 images 目录与 index.*.js 目录在同一位置,你的代码看起来是正确的代码>文件.

Your code looks correct assuming that the images directory is in the same location as the index.*.js files.

你有什么版本的 React Native?从 Images 文档页面:

What version of React Native do you have? From the Images doc page:

可用的 React Native 0.14+.如果你已经生成了你的项目0.13 或更早版本,请阅读此内容.新的资产系统依赖于 Xcode 和 Gradle 的构建钩子,这些钩子包含在用反应原生初始化.如果您在此之前生成了您的项目,您将必须手动将它们添加到您的项目中才能使用新的图像资产系统.有关如何执行此操作的说明,请参阅升级.

Available React Native 0.14+. If you've generated your project with 0.13 or earlier, read this. The new asset system relies on build hooks for Xcode and Gradle that are included in new projects generated with react-native init. If you generated your projects before that, you'll have to manually add them to your projects to use the new images asset system. See Upgrading for instructions on how to do this.

如果您想验证您的 react-native 版本,最简单的方法是从您的项目目录中运行以下 npm 命令:

If you want to verify your react-native version, the easy way to do this is to run the following npm command from your project directory:

npm ls react-native

当前发布版本是 0.15.0.

The current release version is 0.15.0.

确保在更新包后不要忘记运行 react-native upgrade,因为这是将新资产系统的构建挂钩添加到现有项目所必需的.如果您之前更新了您的 react-native 版本而没有这样做,这可能解释了您遇到的问题.

Make sure you don't forget to run react-native upgrade after updating the package as this is required for adding build hooks for the new asset system to existing projects. If you previously updated your react-native version without doing this, that may explain the issue you are having.

如果您碰巧使用 Windows 进行开发,请参阅我的答案到此问题,了解有关如何解决 Windows 上新资产系统错误的详细信息.

If you happen to be using Windows for development, see my answer to this question for details on how to work around a bug with the new asset system on Windows.