React Native学习之Image加载本地图片的坑(iOS)

4,787 阅读1分钟

在使用Image加载本地图片碰到一个小坑,在这里记录下。

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

export default class BillProject extends Component {  
 constructor(props) {
   super(props);
 }
 render() {
     console.log("render");
   var data={src:require('./images/spr_header_background_0.png')}
   var imgLocalUrl = './images/spr_header_background_0.png'
   return (
     <View>
     	<Text>网络图片</Text>
     	<Image style={styles.image_uri}                    
       source={{uri: "http://api.all-appp.com/uploads/uu/20161122/1479774912zuopin9146658userfile.png"}}
       >
       </Image>
       <Text>本地图片成功</Text>
     	<Image style={styles.image_bg}                    
       source={data.src}//source={require(imgLocalUrl)} //这样写则不行
       >
       </Image>
      
     </View>
   );
 }

}
var G_SCREEN_WIDTH = require('Dimensions').get('window').width;
const styles = StyleSheet.create({
  main_view:{
   width:G_SCREEN_WIDTH,
   height:80,
 },
 image_bg:{
   width:G_SCREEN_WIDTH/2,
   height:80,
 },
 image_uri:{
   width:120,
   height:160,
 }
});
AppRegistry.registerComponent('BillProject', () => BillProject);

本地图片加载时使用source={require(imgLocalUrl)} 则不行,会报错。 有的时候会需要把路径先存在变量中再require。 但是require的参数不能是个变量 /(ㄒoㄒ)/~~,会导致路径问题,具体原因有时间再查。

查到官网Note:Image require正确使用姿势

Note

测试结果

原因:在打包脚本执行的时候图片路径就已经打包进去,所以不能用变量的形式。  参考味精的博客:Talk about ReactNative Image Component