2017-08-05 56 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顯示默認圖像。 –