1+ import React , { useState , useEffect , useRef , useCallback , } from 'react'
2+ import { StyleSheet , View , Image } from 'react-native' ;
3+ export interface dataSourceType {
4+ url : string
5+ // onClick?: () => void
6+ }
7+ export interface SwiperProps {
8+ dataSource : dataSourceType [ ] ;
9+ time ?: number ;
10+ width ?: number ;
11+ height ?: number ;
12+ autoplay ?: boolean
13+ }
14+ const Swiper = ( porps : SwiperProps ) => {
15+ const { dataSource = [ ] , time = 3000 , autoplay = true , width = "100%" , height = 130 } = porps
16+ let [ curIndex , setCurIndex ] = useState ( 0 )
17+ let timer = useRef < NodeJS . Timeout | undefined > ( ) ;
18+ const autoPlay = useCallback ( ( ) => {
19+ clearInterval ( timer . current as unknown as number ) ;
20+ timer . current = setInterval ( ( ) => {
21+ if ( curIndex === dataSource . length - 1 ) {
22+ setCurIndex ( 0 ) ;
23+ } else {
24+ setCurIndex ( curIndex + 1 ) ;
25+ }
26+ } , time ) ;
27+ } , [ dataSource , curIndex ] ) ;
28+ useEffect ( ( ) => {
29+ if ( autoplay ) {
30+ autoPlay ( )
31+ }
32+ } , [ autoPlay ] ) ;
33+ useEffect ( ( ) => {
34+ return ( ) => {
35+ clearInterval ( timer . current as unknown as number ) ;
36+ } ;
37+ } , [ ] ) ;
38+ return (
39+ < View style = { StyleSheet . flatten ( [ styles . box , { height } ] ) } >
40+ < View style = { StyleSheet . flatten ( [ styles . banner , { width } ] ) } >
41+ < View style = { StyleSheet . flatten ( [ styles . bannerOut , { marginLeft : curIndex * - 100 + '%' } ] ) } >
42+ { dataSource . map ( ( item : any , index : number ) => {
43+ return < Image style = { styles . tinyLogo } key = { index } source = { {
44+ uri : item . url ,
45+ } } />
46+ } ) }
47+ </ View >
48+ < View style = { styles . dotBox } >
49+ { dataSource . map ( ( _ : any , index : number ) => {
50+ return < View key = { index } style = { StyleSheet . flatten ( [ styles . dot , index === curIndex ? styles . dotSetColor : styles . dotColor ] ) } />
51+ } ) }
52+ </ View >
53+ </ View >
54+ </ View >
55+
56+ )
57+ }
58+ const styles = StyleSheet . create ( {
59+ box : {
60+ margin : 12 ,
61+ height : 130 ,
62+ } ,
63+ banner : {
64+ width : "100%" ,
65+ borderRadius : 25 ,
66+ position : "relative" ,
67+ overflow : "hidden" ,
68+ } ,
69+ bannerOut : {
70+ width : "100%" ,
71+ height : "100%" ,
72+ flexDirection : 'row' ,
73+ alignItems : 'center' ,
74+ marginLeft : 0
75+ } ,
76+ tinyLogo : {
77+ width : "100%" ,
78+ height : "100%" ,
79+ } ,
80+ dotBox : {
81+ width : "100%" ,
82+ flexDirection : 'row' ,
83+ alignItems : 'center' ,
84+ justifyContent : "center" ,
85+ position : "absolute" ,
86+ bottom : 12
87+ } ,
88+ dot : {
89+ width : 10 ,
90+ height : 10 ,
91+ borderRadius : 5 ,
92+ marginTop : 0 ,
93+ marginBottom : 0 ,
94+ marginLeft : 12 ,
95+ marginRight : 12
96+ } ,
97+ dotColor : {
98+ backgroundColor : "lightgray" ,
99+ } ,
100+ dotSetColor : {
101+ backgroundColor : "red" ,
102+ }
103+ } ) ;
104+ export default Swiper
0 commit comments