React-native 之Image的使用

这篇博客介绍了如何使用React-native创建一个图片切换组件。通过示例代码展示了如何加载网络图片,实现上一张、下一张的功能,并处理边界情况。文章包含`MyImage`组件的完整实现,包括状态管理和事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本系列教程是学习东方耀老师的课程中按照教程写的课堂笔记,基础控件的使用其实与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,
      justifyContent:'center',
    },

    img:{
      height:150,
      width:200,
    },
});

AppRegistry.registerComponent('ReactDemo',() => ReactDemo);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值