1. 程式人生 > >基於react-native-swiper 封裝的bannerView

基於react-native-swiper 封裝的bannerView

使用

   <BannerView
                defaultImage={constants.default_img}
                images={this.state.bannerData}
                bannerHeight={150}
                itemOnPress={(i) => {
                    ToastAndroid.show("點選了item===>" + i, ToastAndroid.SHORT)
                }}
            />

程式碼

import React, {Component} from 'react';
import {
    View,
    Image,
    Text,
    TouchableOpacity
} from 'react-native';
import PropType from "prop-types";
import Swiper from "react-native-swiper"

/**
 *
 * Created by yunpeng on
 * Desc:
 */
export default class BannerView extends Component
{
//設定引數型別 static propTypes = { //圖片地址 images: PropType.PropTypes.array, //預設圖片 defaultImage: PropType.PropTypes.string.isRequired, //標題文字 titles: PropType.PropTypes.array, selectDotColor: PropType.PropTypes.string, unSelectDotColor: PropType.PropTypes.string, itemOnPress: PropType.PropTypes.func, bannerHeight: PropType.PropTypes.number, }; static defaultProps = { selectDotColor: '#007aff'
, unSelectDotColor: 'rgba(0,0,0,.2)', bannerHeight: 200, }; render() { return ( <View style={{height: this.props.bannerHeight}}> {this._renderBanner()} </View> ) } /** * 載入banner圖片相關 * @returns {XML} * @private */ _renderBanner() { if (this.props.images && this.props.images.length > 0) { let images = []; for (let i = 0; i < this.props.images.length; i++) { images.push( this._bannerTitle(i) ) } return <Swiper //設定選中點樣式 activeDot={ <View style={{ backgroundColor: this.props.selectDotColor, width: 8, height: 8, borderRadius: 4, marginLeft: 3, marginRight: 3, marginTop: 3, marginBottom: 3, }}/> } //未選中點樣式 dot={<View style={{ backgroundColor: this.props.unSelectDotColor, width: 8, height: 8, borderRadius: 4, marginLeft: 3, marginRight: 3, marginTop: 3, marginBottom: 3, }}/>} //是否展示原點 showsPagination={true} index={0} horizontal={true} paginationStyle={{bottom: 10}} showsButtons={false} autoplayDirection={true} //是否無限輪詢 loop={false} autoplay={false}> {images} </Swiper> } else { return <Image source={{uri: this.props.defaultImage}} style={{flex: 1}}/> } } /** * 載入banner標題 * @private */ _bannerTitle(i) { if (this.props.titles && this.props.titles.length > 0) { return <TouchableOpacity activeOpacity={0.9} onPress={this.props.itemOnPress.bind(this,i)} key={i} style={{height: this.props.bannerHeight}}> <View > <Image source={{uri: this.props.images[i]}} style={{height: this.props.bannerHeight}}/> <View style={{ position: "absolute", justifyContent: 'space-between', alignItems: 'center', bottom: 10, right: 0, left: 0, }}> <Text>{this.props.titles[i]}</Text> </View> </View> </TouchableOpacity> } else { return <TouchableOpacity activeOpacity={0.9} onPress={this.props.itemOnPress.bind(this,i)} key={i} style={{height: this.props.bannerHeight}}> <Image source={{uri: this.props.images[i]}} style={{height: this.props.bannerHeight}}/> </TouchableOpacity> } } }