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

在使用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正确使用姿势

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值