从零学React Native之08Image组件
开发过程中,几乎每个项目都会用到图片. 网络图片加载加载网络图片非常简单, 直接上代码: import React,{ Component } from 'react';
import {
AppRegistry,StyleSheet,View,Image
} from 'react-native';
var imageAddress = 'http://qq.111cn.net/uploads/allimg/140712/22020H9C-22.jpg';
class AwesomeProject extends Component {
render() {
return (
//根View
<View style={styles.container}>
<Image style={styles.imageStyle}
source={{uri:imageAddress}}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: { //根View样式
flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF'
},imageStyle: {
width:100,height:100
}
});
AppRegistry.registerComponent('AwesomeProject',() => AwesomeProject);
运行结果: 本地图片加载在RN开发中,需要预先加载静态的图片资源,如下,其中需要在项目目录下创建image文件夹,里面放置big_star.png。 class AwesomeProject extends Component {
render() {
return (
//根View
<View style={styles.container}>
<Image style={styles.imageStyle}
source={require('./image/big_star.png')}/>
</View>
);
}
}
require等同于使用了var声明了一个变量,等同于在代码顶部预先加载了图片资源. 注意,下面代码运行的时候就会报错 var imageAddress = './image/big_star.png'; //运行阶段赋值
class AwesomeProject extends Component {
//require 在编辑阶段就会处理
render() {
return (
//根View
<View style={styles.container}>
<Image style={styles.imageStyle}
source={require({imageAddress})}/>
</View>
);
}
}
在RN开发中,不允许使用字符串变量来指定需要预先加载的图片的名称.因为React Native在编译代码时处理所有的require声明,还不是在运行时动态的处理,而,var在运行时赋值,所以不能动态加载图片资源. 就会报下面的错误: resizeMode上面我们说了,Image组件必须在样式中声明图片的款和高。如果没有声明,则图片将不会被呈现在界面上。
来看下例子,修改上面的代码,定义三个相同大小的Image控件 引入同一张图片,指定不同的resizeMode。 class AwesomeProject extends Component {
componentWillMount() {
//预加载静态资源
this.image=require('./image/meinv.jpg');
}
render() {
return (
//根View
<View style={styles.container}>
<Image style={[styles.imageStyle,{resizeMode:'cover'}]}
source={this.image}/>
<Image style={[styles.imageStyle,{resizeMode:'contain'}]}
source={this.image}/>
<Image style={[styles.imageStyle,{resizeMode:'stretch'}]}
source={this.image}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: { //根View样式
flex: 1,backgroundColor: 'grey'
},imageStyle: {
width:150,height:150,margin:5,backgroundColor:'white'
}
});
看看运行效果: resizeMode还可以定义在属性上,比style中的优先级要高: <Image style={{height:200,width:200}} resizeMode={Image.resizeMode.cover} source={this.image}/>
看到上面三个模式,可以发现原生的Image控件无法实现等比放大后无丢失显示,我们需要自定义区实现,大家可以参考我的另一篇文章React Native等比放大不丢失图片 其它样式虽然Image组件不是从View组件继承而来的,但是它支持了绝大多数View中的样式键,除了这些还有额外的一些. 回调函数Image也支持onLayout回调函数,与View组件的onLayout函数类似 更多精彩请关注微信公众账号likeDev,公众账号名称:爱上Android。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |