React Native-如何使用图像组件中的uri加载本地图像? [英] React Native - How to load local image using the uri in Image Component?

查看:591
本文介绍了React Native-如何使用图像组件中的uri加载本地图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以使用以下方式加载本地图片:

<Image source={require('folder/image.png')}/>

但是我需要像这样加载图像:

<Image source={{uri: 'folder/image.png'}}/>

它适用于网络映像,但不适用于本地映像,甚至对本地映像也不会产生任何错误,并且不会静默显示该映像.谁能说出如何使用uri属性加载本地图像吗?

It works for network images but it doesn't work for local images and even it does not give any error for local images and silently does not display the image. Can anyone tell how to load the local image using the uri property?

推荐答案

这是在react-native中渲染图像的三种方法, 根据您的情况,您可以对图像进行编码

These are the three ways to render images in react-native , In your case you can encode the image

  • 您可以require图片

source={require('/react-native/img/favicon.png')}

您可以从网络上获取图像

you can get image from web

source={{uri: 'https://facebook.github.io/react-native/docs/assets/favicon.png'}}

或者您可以对图像进行编码

or you can encode the image

source={{uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg=='}}

文档建议如下

export default class DisplayAnImage extends Component {
  render() {
    return (
      <View>
        <Image
          source={require('/react-native/img/favicon.png')}
        />
        <Image
          style={{width: 50, height: 50}}
          source={{uri: 'https://facebook.github.io/react-native/docs/assets/favicon.png'}}
        />
        <Image
          style={{width: 66, height: 58}}
          source={{uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg=='}}
        />
      </View>
    );
  }
}

或者您可以创建一个包含图像编码字符串的json文件 image.json

or you can create a json file that contains the encoded string of the image image.json

{imageString: '64encodedString'}

他们导入文件

import image from 'image.json';

然后图片

<Image source:{{uri:image.imageString}} />

这篇关于React Native-如何使用图像组件中的uri加载本地图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆