无图像的默认来源?

问题描述 投票:0回答:1

我正在为图像源获取有效的uri但是如果我从媒体文件中删除图像,它将返回None文件。

我经常检查图像的无效uri,但这次服务器的图像目录无法呈现图像。

if(!_.isNil(item.img)) { // This checks if uri is null or string

我尝试了defaultSource,但它不起作用;它永远显示白屏

<Image
        fadeDuration={0}
        key={item.id}
        source={{uri: item.img}}
        style={styles.rowImage}
        resizeMode="cover"
        defaultSource={require('../../assets/images/styles.png')}
      />

如果以前的有效uri中的Image不存在,我们如何放置默认图像?

谢谢

image reactjs react-native
1个回答
-1
投票

如果您的uri不存在,您可以使用onError来处理。然后使用setNativeProps以您想要的图像替换您的图像。

使用本地路径:

import resolveAssetSource from 'resolveAssetSource';

...

handleErr(item){

   var imgsrc = require('imagePathHere');

   this.refs[`testimage-${item}`].setNativeProps({
      src: [resolveAssetSource(imgsrc)] //use source for ios instead of src
   });

}

...

<Image
        //ref="testimage"
        ref={`testimage-${item.id}`}
        fadeDuration={0}
        key={item.id}
        source={{uri: item.img}}
        style={styles.rowImage}
        resizeMode="cover"
        defaultSource={require('../../assets/images/styles.png')}
        onError={() => this.handleErr(item.id)}
      />

或者从url使用:

handleErr(item){

   var imgsrc = 'http://blahblah.com/tes.jpg';

   this.refs[`testimage-${item}`].setNativeProps({
      src: [{uri: imgsrc}] //use source for ios instead of src
   });

}

...

<Image
        //ref="testimage"
        ref={`testimage-${item.id}`}
        fadeDuration={0}
        key={item.id}
        source={{uri: item.img}}
        style={styles.rowImage}
        resizeMode="cover"
        defaultSource={require('../../assets/images/styles.png')}
        onError={() => this.handleErr(item.id)}
      />
© www.soinside.com 2019 - 2024. All rights reserved.