基本屬性:
1.resizeMode:枚舉類型,其值為cover、contain、stretch。表示圖片適應(yīng)模式。
2.source:圖片的引用地址,其值為{uri:string}。如果是一個(gè)本地的靜態(tài)資源,那么需要使用
require('image!name')包裹。
3.defaultSource:iOS支持的屬性,表示默認(rèn)的圖片地址。如果網(wǎng)絡(luò)圖片加載完成,將取代defaultSource。
4.onLoad:iOS支持的屬性,加載成功時(shí)觸發(fā)該事件。
5.onLoadEnd:iOS支持的屬性,不管是加載成功還是加載失敗都會觸發(fā)該事件。
6.onLoadStart:iOS支持的屬性,加載開始時(shí)觸發(fā)該事件。
7.onProgress:iOS支持的屬性,加載過程的進(jìn)度事件。
一、加載網(wǎng)絡(luò)圖片
以一個(gè)簡單的圖片瀏覽器為例:
屏幕快照 2016-05-09 下午2.13.52.png
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
View,
Text,
Image,
TouchableOpacity
}= React;
var imgs = ['http://www.ituring.com.cn/bookcover/1442.796.jpg',
'http://www.ituring.com.cn/bookcover/1668.553.jpg',
'http://www.ituring.com.cn/bookcover/1521.260.jpg'];
var MyImage = React.createClass ({
getInitialState: function() {
var imgs = this.props.imgs;
return {
imgs:imgs,
count:0
};
},
goPreView: function() {
var count = this.state.count;
count--;
if (count >= 0) {
this.setState({
count:count
});
}
if (count == -1) {
this.setState({
count:imgs.length - 1
});
}
},
goNextView: function() {
var count = this.state.count;
count++;
if (count < imgs.length) {
this.setState({
count:count
});
}
if (count == imgs.length) {
this.setState({
count:0
});
}
},
render: function() {
return(
<View style={styles.flex}>
<View style={styles.image}>
<Image style={styles.img}
source={{uri:this.state.imgs[this.state.count]}}
resizeMode="contain"
/>
</View>
<View style={styles.btns}>
<TouchableOpacity onPress={this.goPreView}>
<View style={styles.btn}>
<Text>上一張</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.goNextView}>
<View style={styles.btn}>
<Text>下一張</Text>
</View>
</TouchableOpacity>
</View>
</View>
);
},
});
var IMG = React.createClass ({
render: function() {
return(
<View style={[styles.flex, {marginTop:40}]}>
<MyImage imgs = {imgs}></MyImage>
</View>
);
},
});
var styles = StyleSheet.create ({
flex: {
flex:1,
alignItems:'center'
},
image: {
borderWidth:1,
borderColor:'#ccc',
width:300,
height:200,
borderRadius:5,
justifyContent:'center',
alignItems:'center'
},
img: {
height:150,
width:200
},
btns: {
flexDirection:'row',
justifyContent:'center',
marginTop:20
},
btn: {
width:60,
height:30,
borderWidth:1,
borderColor:'#0089FF',
justifyContent:'center',
alignItems:'center',
borderRadius:3,
marginRight:20
}
});
AppRegistry.registerComponent('InformationServicesRN', () => IMG);
二、加載本地圖片
React Native建議使用1和2的加載方式,而不希望使用方式3在運(yùn)行時(shí)才分析靜態(tài)資源
//好的加載方式
1.<Image source={require('image!my-icon')}/>
2.var icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive')
<Image source={icon}/>
//不好的加載方式
3.var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('image!' + icon)}/>