UNPKG

@td-design/react-native

Version:

react-native UI组件库

65 lines (62 loc) 1.79 kB
import { useEffect, useRef } from 'react'; import { useMemoizedFn, useSafeState } from '@td-design/rn-hooks'; export default function useCarousel(_ref) { let { auto, width, duration, count } = _ref; const scrollViewRef = useRef(null); const timer = useRef(); const [currentIndex, setCurrentIndex] = useSafeState(0); const loop = useMemoizedFn(() => { setCurrentIndex(index => index === count - 1 ? 0 : index + 1); }); // 用户手动滚动开始时,停止轮播 const clearTimer = useMemoizedFn(() => { clearInterval(timer.current); timer.current = undefined; }); useEffect(() => { if (!auto) return; timer.current = setInterval(loop, duration); return () => clearTimer(); }, [loop, auto, duration]); useEffect(() => { var _scrollViewRef$curren; (_scrollViewRef$curren = scrollViewRef.current) === null || _scrollViewRef$curren === void 0 ? void 0 : _scrollViewRef$curren.scrollTo({ animated: true, y: 0, x: width * currentIndex }); }, [currentIndex]); const startTimer = () => { timer.current = setInterval(loop, duration); }; // 在ScrollView滚动结束后,修改当前index const onScrollEnd = e => { const { x } = e.nativeEvent.contentOffset; const index = Math.ceil(x / width); setCurrentIndex(index); if (auto && !timer.current) { startTimer(); } }; // 如果是自动轮播,手指离开屏幕后,重新开始轮播 const onTouchEnd = () => { if (auto && !timer.current) { startTimer(); } }; return { scrollViewRef, currentIndex, onTouchStart: clearTimer, onTouchEnd: useMemoizedFn(onTouchEnd), onScrollEnd: useMemoizedFn(onScrollEnd) }; } //# sourceMappingURL=useCarousel.js.map