本系列教程是学习东方耀老师的课程中按照教程写的课堂笔记,基础控件的使用其实与Android及iOS类似,并没有太大的区别,因此此处只记录代码,不做更多分析,等后期项目实战阶段再详细分析。
界面上有两个按钮,上面有三张图片,点击“上一张”、“下一张”切换,当切换到最后一张时不能再点击下一张,当切换到第一张时不能点击上一张,效果图如下:
index.ios.js的代码如下:
import React,{Component} from 'react'; import { AppRegistry,StyleSheet,Text,View,Image,PiexRatio,TouchableOpacity,} from 'react-native'; var imgs=[ 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png','https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1746876025,1511395716&fm=80&w=179&h=119&img.JPEG','https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=2769333013,754789968&fm=80&w=179&h=119&img.JPEG' ]; class ReactDemo extends Component { render() { return ( <View style={[styles.flex,{marginTop:45}]}> <MyImage imgs={imgs}></MyImage> </View> ); } } class MyImage extends Component { constructor(props) { super(props); this.state = { count:0,imgs:this.props.imgs,}; } render(){ return( <View style={[styles.flex,{alignItems:'center'}]}> <View> <Image style={styles.img} resizeMode="contain" source={{uri:this.state.imgs[this.state.count]}} /> </View> <View style={styles.btns}> <TouchableOpacity onPress={this.goPreview.bind(this)}> <View style={styles.btn}> <Text>上一张</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={this.goNext.bind(this)}> <View style={styles.btn}> <Text>下一张</Text> </View> </TouchableOpacity> </View> </View> ); } goPreview(){ var count=this.state.count; count--; if (count >= 0) { this.setState({count:count}); } } goNext(){ var count=this.state.count; count++; if (count < this.state.imgs.length) { this.setState({count:count}); } } } const styles = StyleSheet.create({ flex:{ flex:1,},btn:{ width:60,height:30,borderColor:'#0089FF',borderWidth:1,justifyContent:'center',borderRadius:3,marginRight:20,btns:{ flexDirection:'row',marginTop:20,img:{ height:150,width:200,}); AppRegistry.registerComponent('ReactDemo',() => ReactDemo);