React-native: Images not showing in android device; but shows perfectly in emulator

末鹿安然 提交于 2020-01-12 04:54:11

问题


I am working on a sample react native project. And almost all features except the <Image source=''/> work well with it. The image shows well in android emulator supplied with android studio and genymotion, but does not work on any real devices (moto G3 turbo, nexus 5, galaxy s4 etc...). I don't know what went wrong with my code. Here is my code

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image
} from 'react-native';

class ImageTester extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Double tap R on your keyboard to reload,{'\n'}
          Shake or press menu button for dev menu
        </Text>
        <Image source={require('./img/first_image.png')}></Image>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

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

project structure:

React-native version : react-native: 0.32.1


回答1:


The problem was with my bundle packaging command. As @luwu said in his comment, I checked this, and surprised that there is no difference with mine. Then only I noticed a message while running the command

"Assets destination folder is not set, skipping..."

That message was bit confusing since bundle was already created in the assets folder. The 'Assets' in that messages actually indicates my images. And I solved the issues with the following command:

react-native bundle --platform android --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --dev false --reset-cache --assets-dest android/app/src/main/res/



回答2:


Another solution for the same issue of assets not bundled in development.

Add the following line to your app/build.gradle file in the section project.ext.react:

project.ext.react = [
    ... other properties
    bundleInDebug: true // <-- add this line
]

From the docs in the starter project gradle file:

By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the bundle directly from the development server.



来源:https://stackoverflow.com/questions/39385129/react-native-images-not-showing-in-android-device-but-shows-perfectly-in-emula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!