2017-08-05 95 views
1

我需要根据数组的长度来呈现图像标记在一个循环中, 我的形象标签类似于这样负载缩略图 - 阵营本地

<Image 
      style={{width: 50, height: 50}} 
      source={{uri: 'https://facebook.github.io/react/img/logo_og1.png'}} 
//if image fails to load from the uri then load from'./img/favicon.png' 
      onError={(error) => {console.log('loadinf',error)}} 
     /> 

如果在从乌里获取发生错误即有时404错误重试或显示默认本地图像。 如何在原生态中做到这一点?

回答

2

使用defaultSource属性在真实图像的位置放置一个加载图像,但它仅在iOS时可用。我们可以实现你写的其他东西,它应该显示一个本地图像,以防它无法通过以下方法从互联网加载图像。

  1. 将原始图像URI存储在状态中。
  2. 使用该图像的source状态中的该URI。
  3. onError函数被调用时,将此状态变量更改为本地图像。

例子:

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

export default class Demo extends Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     image: { 
     uri: 'something demo' 
     } 
    } 
    } 

    render() { 
    return <View> 
     <Image 
      source={ this.state.image } 
      onError={(a) => { 
       this.setState({ 
        image: require('image.png') 
       }); 
      }} 
      style={{ height: 100, width: 100 }} 
     /> 
    </View> 
    } 
} 

一个肮脏的黑客的重试的形象将是这样的:

let counter = 0; 
export default class reactNativePange extends Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
      image: { 
       uri: 'something demo' 
      }, 
      failed: false 
     } 
    } 

    render() { 
     return (
      <View style={styles.container}> 
       <Image 
        source={ this.state.failed ? require('./image.png') : { uri: 'something demo' } } 
        onError={(a) => { 
         if(counter >= 3) { 
          this.setState({ 
           failed: true 
          }); 
         } else { 
          counter++; 
          this.setState({ 
           failed: true 
          }); 
          setTimeout(() => { 
           this.setState({ 
            failed: false 
           }); 
          }, 1) 
         } 
        }} 
        style={{ height: 100, width: 100 }} 
       /> 
      </View> 
     ); 
    } 
} 

正如我所说,这是一个肮脏的黑客的图像可能在重试期间闪烁。

+0

你的答案将适用于单幅图像(1图像标签和1个状态变量),但我的场景我有1个状态变量和对象是巨大的数据(100个对象在数组中,并基于数组计数视图将被呈现动态),我需要循环和更新对象,无论它是否是错误的。有没有简单的方法来实现相同的目标。 –

+0

您可以通过制作渲染此图像的组件来轻松实现此目的。例如。 'CustomImage'可以是一个组件,它可以有一个支持URI的属性,上面的代码可以调整到该组件中。这样你就不必手动维护100个状态变量。 :) –

+0

感谢@Jagjot它的作品'导出默认类CustomImage扩展组件{props){0} {0} {0} this.state = {imageFailed:false}; } 渲染(){ 回报( <图像 风格= {{高度:100,宽:100}} 源= {this.state.imageFailed要求( “./虚设image.jpg的”)?: {error:this.props.imageuri}} onError = {(error)=> {this.setState({imageFailed:true})}} key = {this.props.imageuri} /> ); } }' 如果出现错误,是否可以重试从同一个uri获取图像?现在iam显示默认图像。 –