React Native-10.React Native Image组件详解
Image组件简介老话说,没图你说个xx,可见图片在用户感官上的重要性。RN中,Image组件目前支持的属性如下:
加载网络图片我们做一个图片浏览器的小demo : RN中不像web开发那样会默认显示图片,在浏览器中,图片的大小开始是0*0,当图片下载完成后,会按照图片的大小渲染,这时你就会看到图片的加载闪烁,但这是不好的用户体验,因此,在RN中,Image组件的默认大小是0,是不显示图片的。我们需要给定图片的宽高或者知道图片的宽高财能展示图片。因此,我们一开始就可以是用占位符来代替,这样就没有了web的闪烁。这里我们设置主题的图片模式为 resizeMode = “contain”,这样的话,我们的图片就会在指定大小内适应缩放。source的值为{uri: this.state.imgs[this.state.count]},其中uri是根据this.state.count变化的,this.state.count代表数组中的索引。代码如下: 'use strict';
var React = require('react-native');
var {
AppRegistry,StyleSheet,Text,View,Image,TouchableOpacity,} = React;
var imgs = [
'http://pic15.nipic.com/20110702/1410048_183203957000_2.jpg','http://pic1a.nipic.com/2008-10-06/20081069818327_2.jpg','http://pic17.nipic.com/20111019/7745445_223209748000_2.jpg',]
var MyImage = React.createClass({
getInitialState : function(){
var imgs = this.props.imgs;
return{
imgs : imgs,count : 0,};
},goNext : function(){
var count = this.state.count;
count++;
if(count < imgs.length){
this.setState({
count: count
});
}
},goPreview: function() {
var count = this.state.count;
count--;
if(count >= 0){
this.setState({
count:count
});
}
},render: function(){
return(
<View style = {[styles.flex,{marginTop: 25}]}>
<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}
style = {[styles.btn]}>
<Text>
上一张
</Text>
</TouchableOpacity>
<TouchableOpacity onPress = {this.goNext}
style = {[styles.btn]}>
<Text>
下一张
</Text>
</TouchableOpacity>
</View>
</View>
);
}
})
var styles = StyleSheet.create({
flex: {
flex: 1,alignItems: 'center',},image: {
borderWidth: 1,width:300,height: 200,borderRadius: 5,justifyContent: 'center',img : {
height: 150,width: 200,btns : {
flexDirection: 'row',marginTop :20,btn : {
width : 60,height: 30,borderColor: '#0089ff',borderWidth: 1,alignItems : 'center',borderRadius : 3,marginRight: 20,}
})
var wxsPrj = React.createClass({
render: function() {
return (
<View sytle = {[styles.flex,{marginTop:40}]}>
<MyImage imgs = {imgs}></MyImage>
</View>
);
}
})
AppRegistry.registerComponent('wxsPrj',() => wxsPrj);
效果: 加载本地图片先说语法: //好的加载方式
<Image source = {require(image!imageName)}/>
//不好的加载方式
var icon = this.props.active ? 'imageName' : 'imageName2';
<Image source = {require('image!'+icon)}>
//好的加载方式
var icon = this.props.active ? require('image!imageName'):require('image!imageName2');
<Image source = {icon}/>
第二种之所以不好,是因为它运行时去分析静态资源,这个没有必要。 在项目中添加本地图片,需要重启模拟器才可以看到效果。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- Internationalization with the Dojo Toolkit
- DI与IOC——控制反转容器和依赖注入模式
- w3svc服务启动 不了,错误 1068:依赖服务或组件无法启动
- fastjson 转换long型报错
- cocos2dx 3.3 AssetsManager简单分析
- iphone – 如何在NavBar中以编程方式设置图片?
- c – XMLString :: transcode的目的
- ruby-on-rails-3 – 我应该在rails3中存储api密钥?
- c# – 我应该处理工厂模式类中的异常还是让它们向上传播?
- BB FlashBack Pro v4.0.0.2375 incl. crack/serial by ADMI