0

我有一個問題。我在Image中使用onLoad,onLoadStart和onLoadEnd。我想等服務器獲取響應鏈接圖像並顯示圖像時,添加加載。但它不斷地猛拉。反應本機檢測加載圖像

constructor (props) { 
    super(props) 
    this.state = {loading: true}} 

    return(
    <Image 
     onLoad={(e) => this.setState({loading: true})} 
     onError={(e) => this.setState({loading: false})} 
     onLoadStart={(e) => this.setState({loading: false})} 

     source={this.state.loading ? require('../../img/loading.gif') : { 
     uri: getBestUrl(artwork)}} 
     style={styles.artworkImage} 
     resizeMode={Image.resizeMode.cover} 
     />) 

回答

0

你是從構造函數返回一個圖像還是你沒有發佈所有的代碼?

現在的問題,我認爲它不會這樣工作,因爲它似乎總是會改變狀態,而加載您的'loading.gif'或您的uri圖像。你是否也爲你的圖像設置高度和重量?這是需要的,因爲您可以在文檔中看到

與靜態資源不同,您將需要手動指定圖像的 尺寸。

https://facebook.github.io/react-native/docs/images.html#network-images

也許你可以存儲在你的狀態的圖像路徑,按照狀態值做出有條件的渲染。例如:

... 
this.state = { 
imagePath: null, 
} 
... 

this.setState({ 
imagePath: getBestUrl(artwork); 
}); 
... 

{ 
this.state.imagePath ? <Image uri={require(this.state.imagePath)} /> : <Image uri={require('loading.gif')} 
} 

考慮上面的代碼僅僅是一個例子來表達這個想法。

希望這可以爲你帶來價值。

+0

感謝您的想法。我只是添加了我的代碼。你可以看看。我沒有做過一個例子 –