mh-rn-component
Version:
253 lines (248 loc) • 7.6 kB
Flow
import React, { useEffect, useRef, useState } from 'react'
import { View, Text, ScrollView, StyleSheet } from 'react-native'
import { LayoutType, ColorBg, OffsetType } from "./types"
type Props = {
defaultIndex?: number
autoplay?: number | boolean,//默认为false true的时候为2000ms
loop?: boolean
children?: any,
showIndicators?: boolean,//是否显示指示器
indicatorColor?: string,//指示器颜色
numberIndicators?: boolean,//是否使用数字指示器
customIndicators?: () => JSX.Element
onChange?: (index:number) => void
}
const Swiper = ({ children, loop = true, defaultIndex = 0, autoplay = false, ...rest }: Props) => {
const defaultProps = {
horizontal: true,// 是否是水平方向 排列默认false
pagingEnabled: true,// 是否成视图的倍数滚动 默认false horizontal:false时pagingEnabled在 Android 上不支持
showsHorizontalScrollIndicator: false,// 是否显示水平方向的滚动条
showsVerticalScrollIndicator: false,// 是否显示垂直方向的滚动条
bounces: false,//ios 末尾是否可以弹性地拉动一截
scrollsToTop: false,//ios 点击状态栏的时候视图会滚动到顶部。默认值为 true
removeClippedSubviews: false,
automaticallyAdjustContentInsets: false,
}
const total: number = Object.keys(children).length
const [index, setIndex] = useState(0)
// 载体宽高
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
// 初始滚动位置
const [offset, setOffset] = useState<OffsetType>({ x: 0, y: 0 })
// 起始位置备份 这个是用来记录当前scroll移动到哪儿了的
const [internals, setInternals] = useState<OffsetType>({ x: 0, y: 0 })
// ScrollViewref
const refScrollView = useRef<any>(null)
// autoplayRef
const autoplayTimer = useRef<any>(null)
const onLayout = (e: any) => {
const { width, height } = e.nativeEvent.layout
setWidth(width)
setHeight(height)
if (loop) {
// loop的时候设置默认值
setOffset({ ...offset, ...{ x: width } })
setInternals({ ...internals, ...{ x: width } })
}
}
const loopJump = (num: number, offset: OffsetType) => {
const scrollView: any = refScrollView.current
const loopJumpTimer = setTimeout(() => {
if (scrollView.setPageWithoutAnimation) {
scrollView.setPageWithoutAnimation(num + 1)
} else {
if (num === 0) {
scrollView.scrollTo({
...offset,
animated: false
})
} else if (num === total - 1) {
scrollView.scrollTo({
...offset,
animated: false
})
}
}
clearTimeout(loopJumpTimer)
}, scrollView.setPageWithoutAnimation ? 50 : 300)
}
const scrollBy = (step: number) => {
const scrollView: any = refScrollView.current
const diff = step + index + (loop ? 1 : 0)
const x = diff * width
scrollView && scrollView.scrollTo({ x, animated: true })
}
const autoplayFunc = () => {
const autoplayTime = typeof autoplay === 'boolean' ? 2000 : autoplay
autoplayTimer.current && clearTimeout(autoplayTimer.current)
// 我是用index来操控的
autoplayTimer.current = setTimeout(() => {
if (index < total + 1) {
// 移动几个
scrollBy(1)
}
}, autoplayTime)
}
/**
* index相当的重要,获取方式再斟酌一下
* @param offset 偏移量
*/
const updateIndex = (offset: OffsetType, cb?: Function) => {
// Android ScrollView will not scrollTo certain offset when props change
let _index = index
const step = width
const diff = offset.x - internals.x
_index = _index + Math.round(diff / step)
// 循环播放
if (loop) {
if (_index <= -1) {
_index = total - 1
offset.x = step * total
loopJump(_index, offset)
} else if (_index >= total) {
_index = 0
offset.x = step
loopJump(_index, offset)
}
}
setOffset({ ...offset })
setInternals({ ...offset })
setIndex(_index)
rest.onChange && rest.onChange(_index)
}
// 用width结合useEffect 模拟元素加载完成的生命周期
useEffect(() => {
if (width !== 0) {
autoplay && autoplayFunc()
}
scrollBy(defaultIndex)
}, [width])
// 监听改变 因为state是一个异步 autoplay专用
useEffect(() => {
if (width !== 0 && autoplay) {
autoplayFunc()
}
}, [index])
// 开始拖动
const onScrollBegin = (e: any) => {
if (!e.nativeEvent.contentOffset) {
e.nativeEvent.contentOffset = {
x: e.nativeEvent.position * width
}
}
if (internals.x === 0) {
setInternals({ ...e.nativeEvent.contentOffset })
}
}
const onScrollEnd = (e: any) => {
if (!e.nativeEvent.contentOffset) {
e.nativeEvent.contentOffset = {
x: e.nativeEvent.position * width
}
}
updateIndex(e.nativeEvent.contentOffset)
}
const renderScrollView = () => {
const pages = Object.keys(children)
if (loop) {
pages.unshift(`${total - 1}`)
pages.push('0')
}
return (
<ScrollView
ref={refScrollView}
{...defaultProps}
contentOffset={offset}
onScrollBeginDrag={onScrollBegin}
onMomentumScrollEnd={onScrollEnd}
>
{pages.map((item, i) => {
return <View key={i} style={[{ width: width, backgroundColor: ColorBg[i] }]}>
{children[item]}
</View>
})}
</ScrollView>
)
}
// dot指示器
const indicatorsView = () => {
const childrenArr = Object.keys(children)
return (<View style={styles.indicators}>
{
childrenArr.map((item, i) => {
return (<View key={i}
style={[
styles.indicators_item,
i === index && styles.active_indicators_item,
i === index && {
backgroundColor: rest.indicatorColor ? rest.indicatorColor : '#fff'
},
{
marginRight: i === total - 1 ? 0 : 6,
}]}></View>)
})
}
</View>)
}
//数字指示器
const numberIndicatorsView = () => {
return (<View style={[styles.numberIndicators]}>
<Text style={{ color: "#fff", fontSize: 18 }}>
{index + 1}/{total}
</Text>
</View>)
}
// render
return (
<View style={styles.swiper} onLayout={onLayout}>
{renderScrollView()}
{/* 指示器 */}
{rest.customIndicators ? rest.customIndicators() : (<View>
{(rest.showIndicators && !rest.numberIndicators) && indicatorsView()}
{(rest.showIndicators && rest.numberIndicators) && numberIndicatorsView()}
</View>)}
</View>
)
}
const styles = StyleSheet.create({
swiper: {
flex: 1,
position: 'relative',
backgroundColor: "#648e93"
},
swiper_item: {
backgroundColor: "#f1939c"
},
indicators: {
width: "100%",
flexDirection: "row",
position: "absolute",
bottom: 10,
alignItems: 'center',
justifyContent: "center",
},
indicators_item: {
width: 10,
height: 10,
borderRadius: 5,
backgroundColor: "#ebedf0",
opacity: 0.3,
marginRight: 6,
},
active_indicators_item: {
opacity: 1,
},
numberIndicators: {
position: "absolute",
right: 5,
bottom: 10,
alignItems: "center",
flexDirection: "row",
justifyContent: "center",
backgroundColor: "rgba(255,255,255,0.3)",
paddingLeft: 10,
paddingRight: 10,
},
})
export default React.memo(Swiper)