Loading圖適用于網絡圖片加載失敗或者加載過程中的占位圖,以下先展示最簡單的網絡請求占位圖:
請求的圖片地址:
const URL = 'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1333472173,1434096058&fm=80&w=179&h=119&img.JPEG';
render方法:
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
Loading圖的模擬加載
</Text>
{this.renderLoadImg()}
<Text style={styles.instructions}>
1秒以后,會請求網絡數據
</Text>
</View>
);
}
renderLoadImg方法的解釋:
當網絡數據加載完成后,顯示所加載的圖片;沒有加載完成的時候,顯示Loading圖。
renderLoadImg(){
let img;
if(this.state.imgUrl){
img = (<Image source={{uri:this.state.imgUrl}} style={{width:200,height:200}} />);
}else{
img = (<Image source={require('./img/loading.png')} style={{width:200,height:200}} />)
}
return img;
}
模擬漫長的網絡請求過程:用到了setTimeout方法,模擬1s后請求成功。
componentDidMount(){
setTimeout(()=>{
this.setState({
imgUrl:URL
})
},1000)
}
完整代碼如下:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
const URL = 'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1333472173,1434096058&fm=80&w=179&h=119&img.JPEG';
export default class imgRes extends Component {
constructor(props){
super(props);
this.state = {
imgUrl:null
}
}
componentDidMount(){
setTimeout(()=>{
this.setState({
imgUrl:URL
})
},1000)
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
Loading圖的模擬加載
</Text>
{this.renderLoadImg()}
<Text style={styles.instructions}>
1秒以后,會請求網絡數據
</Text>
</View>
);
}
renderLoadImg(){
let img;
if(this.state.imgUrl){
img = (<Image source={{uri:this.state.imgUrl}} style={{width:200,height:200}} />);
}else{
img = (<Image source={require('./img/loading.png')} style={{width:200,height:200}} />)
}
return img;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('imgRes', () => imgRes);
效果如下:
示例效果
使RN支持gif圖設置方法:
在android\build.gradle中dependencies依賴中添加如下代碼:
compile 'com.facebook.fresco:animated-gif:0.13.0'
這樣就可以引用gif圖片了。。。。