react-native中使用ScrollView组件自己封装走马灯

Orenda ·
更新时间:2024-09-20
· 719 次阅读

使用ScrollView替代View可以实现安全范围内的滚动

showsVerticalScrollIndicator隐藏滚动条

制作轮播图 import { View, Text, StatusBar, SafeAreaView, StyleSheet, ScrollView, Image, Dimensions, } from 'react-native'; const screenWidth = Math.round(Dimensions.get('window').width); const App = () => { const scrollRef = useRef(); const [currentIndex, setCurrentIndex] = useState(0); useEffect(() => { //初始化后,页面渲染完,立即滚动到真正的第一页 setTimeout(() => { scrollRef.current.scrollTo({x: screenWidth, y: 0, animated: false}); }, 0); }, [scrollRef]); useEffect(() => { scrollRef.current.currentIndex = currentIndex; }, [currentIndex, scrollRef]); //定时器,定时滚动 useEffect(() => { console.log('初始化了定时器'); setInterval(() => { const offset = screenWidth * (scrollRef.current.currentIndex + 2); scrollRef.current.scrollTo({x: offset, y: 0, animated: true}); }, 3000); }, [scrollRef]); const scrollEnd = useCallback(event => { let index = event.nativeEvent.contentOffset.x / screenWidth; // index = Math.round(index); // console.log(index); if (index === 0) { setCurrentIndex(() => 3); //这是最后一页,应该去到真实的最后一页 const offset = screenWidth * images.length; scrollRef.current.scrollTo({x: offset, y: 0, animated: false}); } else if (index === 5) { setCurrentIndex(() => 0); //这是第一页 const offset = screenWidth; scrollRef.current.scrollTo({x: offset, y: 0, animated: false}); } else { setCurrentIndex(() => index - 1); } }, []); return (
{/* 假的最后一张 */} {/* 真实的内容 */} {images.map((item, index) => ( ))} {/* 假的第一张 */} {currentIndex} ); };

样式:

const S = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f1f1f1', overflow: 'hidden', }, content: { flex: 1, backgroundColor: 'red', }, scroll: { width: '100%', height: 200, backgroundColor: '#fff', }, scrollWrap: { width: '600%', height: 200, flexDirection: 'row', }, image: { width: (1 / 6) * 100 + '%', height: 200, }, });
作者:Georgia fab



封装 native 走马灯 scrollview React

需要 登录 后方可回复, 如果你还没有账号请 注册新账号