在 React Native 中建立自訂輪播是為應用程式添加視覺效果和互動性的好方法。在本部落格中,我們將探索如何使用 React Native 的 Animated 和 Reanimated 庫建立包含自動滾動功能的輪播。我們還將實現一個帶有動畫點和優雅的圖像過渡效果的分頁系統。
概述
在本教學中,我們將介紹以下內容:
- 設定自訂輪播元件。
- 使用 Reanimated 實現流暢的動畫和內插。
- 自動捲動功能,可在影像之間自動旋轉。
- 建立一個帶有動畫點指示器的分頁系統。
我們將建構什麼:
- 有動畫轉場的水平滾動輪播。
- 當使用者與輪播互動時自動滾動暫停。
- 根據目前可見項目更新的分頁點。
讓我們開始吧!
1. 設定輪播組件
我們首先建立 CustomCarousel 元件,它將容納輪播的核心邏輯。主要元素包括:
- 用於渲染項目的 Animated.FlatList。
- 使用 setInterval 的自動滾動機制。
- Reanimated的scrollTo和useSharedValue用於動畫轉換。
/* eslint-disable react-native/no-inline-styles */ import React, { useEffect, useRef, useState } from 'react'; import { StyleSheet, View, useWindowDimensions } from 'react-native'; import Animated, { scrollTo, useAnimatedRef, useAnimatedScrollHandler, useDerivedValue, useSharedValue, } from 'react-native-reanimated'; import { hpx } from '../../helpers'; import Pagination from './Pagination'; import RenderItem from './RenderItem'; import { animals } from './constants'; const CustomCarousel = () => { const x = useSharedValue(0); const [data, setData] = useState(animals); const { width } = useWindowDimensions(); const [currentIndex, setCurrentIndex] = useState(0); const [paginationIndex, setPaginationIndex] = useState(0); const ref = useAnimatedRef(); const [isAutoPlay, setIsAutoPlay] = useState(true); const interval = useRef(); const offset = useSharedValue(0); console.log('CURRENT_CAROUSEL_ITEM?', paginationIndex); const onViewableItemsChanged = ({ viewableItems }) => { if (viewableItems[0].index !== undefined && viewableItems[0].index !== null) { setCurrentIndex(viewableItems[0].index); setPaginationIndex(viewableItems[0].index % animals.length); } }; const viewabilityConfig = { itemVisiblePercentThreshold: 50, }; const viewabilityConfigCallbackPairs = useRef([{ viewabilityConfig, onViewableItemsChanged }]); const onScroll = useAnimatedScrollHandler({ onScroll: (e) => { x.value = e.contentOffset.x; }, onMomentumEnd: (e) => { offset.value = e.contentOffset.x; }, }); useDerivedValue(() => { scrollTo(ref, offset.value, 0, true); }); useEffect(() => { if (isAutoPlay === true) { interval.current = setInterval(() => { offset.value += width; }, 4000); } else { clearInterval(interval.current); } return () => { clearInterval(interval.current); }; }, [isAutoPlay, offset, width]); return ( <view style="{styles.container}"> <animated.flatlist ref="{ref}" style="{{" height: hpx flexgrow: onscrollbegindrag="{()"> { setIsAutoPlay(false); }} onScrollEndDrag={() => { setIsAutoPlay(true); }} onScroll={onScroll} scrollEventThrottle={16} horizontal bounces={false} pagingEnabled showsHorizontalScrollIndicator={false} viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current} onEndReached={() => setData([...data, ...animals])} onEndReachedThreshold={0.5} data={data} keyExtractor={(_, index) => `list_item${index}`} renderItem={({ item, index }) => { return <renderitem item="{item}" index="{index}" x="{x}"></renderitem>; }} /> <pagination paginationindex="{paginationIndex}"></pagination> </animated.flatlist></view> ); }; export default CustomCarousel; const styles = StyleSheet.create({ container: { flex: 1, }, buttonContainer: { justifyContent: 'center', alignItems: 'center', flexDirection: 'row', gap: 14, }, });
2. 分頁組件
分頁元件顯示點來指示目前活動的幻燈片。每個點的不透明度都會根據輪播的當前索引而變化。
import React from 'react'; import { StyleSheet, View } from 'react-native'; import { hpx } from '../../helpers'; import Dot from './Dot'; import { animals } from './constants'; const Pagination = ({ paginationIndex }) => { return ( <view style="{styles.container}"> {animals.map((_, index) => { return <dot index="{index}" key="{index}" paginationindex="{paginationIndex}"></dot>; })} </view> ); }; export default Pagination; const styles = StyleSheet.create({ container: { flexDirection: 'row', marginTop: hpx(16), justifyContent: 'center', alignItems: 'center', }, });
3. 點組件
Dot 元件處理分頁系統中每個點的外觀。它會根據點是否處於活動狀態(目前索引)來變更其樣式。
import React from 'react'; import { StyleSheet, View } from 'react-native'; import { Colors } from '../../assets'; import { hpx, wpx } from '../../helpers'; const Dot = ({ index, paginationIndex }) => { return <view style="{paginationIndex" index styles.dot : styles.dotopacity></view>; }; export default Dot; const styles = StyleSheet.create({ dot: { backgroundColor: Colors.white, height: hpx(3), width: wpx(12), marginHorizontal: 2, borderRadius: 8, }, dotOpacity: { backgroundColor: Colors.white, height: hpx(3), width: wpx(12), marginHorizontal: 2, borderRadius: 8, opacity: 0.5, }, });
4. RenderItem 元件
RenderItem 元件顯示每個輪播項目。它利用 Reanimated 的插值函數來為專案滾動時的不透明度設定動畫。
import React from 'react'; import { StyleSheet, useWindowDimensions, View } from 'react-native'; import Animated, { Extrapolation, interpolate, useAnimatedStyle } from 'react-native-reanimated'; import { hpx, nf, SCREEN_WIDTH, wpx } from '../../helpers/Scale'; const RenderItem = ({ item, index, x }) => { const { width } = useWindowDimensions(); const animatedStyle = useAnimatedStyle(() => { const opacityAnim = interpolate( x.value, [(index - 1) * width, index * width, (index + 1) * width], [-0.3, 1, -0.3], Extrapolation.CLAMP ); return { opacity: opacityAnim, }; }); return ( <view style="{{" width> <animated.image resizemode="cover" source="{{" uri: item.image style="{[styles.titleImage," animatedstyle></animated.image> </view> ); }; export default RenderItem; const styles = StyleSheet.create({ titleImage: { width: SCREEN_WIDTH - wpx(32), // adjust the width of the image and horizontal padding height: hpx(194), alignSelf: 'center', borderRadius: nf(16), }, });
5. 自動捲動
自動滾動功能是透過setInterval來實現的。此方法可確保輪播每 4 秒自動從一張投影片移至下一張投影片。如果使用者透過拖曳與輪播交互,自動滾動就會暫停。
6. 常數檔
/* eslint-disable react-native/no-inline-styles */ import React, { useEffect, useRef, useState } from 'react'; import { StyleSheet, View, useWindowDimensions } from 'react-native'; import Animated, { scrollTo, useAnimatedRef, useAnimatedScrollHandler, useDerivedValue, useSharedValue, } from 'react-native-reanimated'; import { hpx } from '../../helpers'; import Pagination from './Pagination'; import RenderItem from './RenderItem'; import { animals } from './constants'; const CustomCarousel = () => { const x = useSharedValue(0); const [data, setData] = useState(animals); const { width } = useWindowDimensions(); const [currentIndex, setCurrentIndex] = useState(0); const [paginationIndex, setPaginationIndex] = useState(0); const ref = useAnimatedRef(); const [isAutoPlay, setIsAutoPlay] = useState(true); const interval = useRef(); const offset = useSharedValue(0); console.log('CURRENT_CAROUSEL_ITEM?', paginationIndex); const onViewableItemsChanged = ({ viewableItems }) => { if (viewableItems[0].index !== undefined && viewableItems[0].index !== null) { setCurrentIndex(viewableItems[0].index); setPaginationIndex(viewableItems[0].index % animals.length); } }; const viewabilityConfig = { itemVisiblePercentThreshold: 50, }; const viewabilityConfigCallbackPairs = useRef([{ viewabilityConfig, onViewableItemsChanged }]); const onScroll = useAnimatedScrollHandler({ onScroll: (e) => { x.value = e.contentOffset.x; }, onMomentumEnd: (e) => { offset.value = e.contentOffset.x; }, }); useDerivedValue(() => { scrollTo(ref, offset.value, 0, true); }); useEffect(() => { if (isAutoPlay === true) { interval.current = setInterval(() => { offset.value += width; }, 4000); } else { clearInterval(interval.current); } return () => { clearInterval(interval.current); }; }, [isAutoPlay, offset, width]); return ( <view style="{styles.container}"> <animated.flatlist ref="{ref}" style="{{" height: hpx flexgrow: onscrollbegindrag="{()"> { setIsAutoPlay(false); }} onScrollEndDrag={() => { setIsAutoPlay(true); }} onScroll={onScroll} scrollEventThrottle={16} horizontal bounces={false} pagingEnabled showsHorizontalScrollIndicator={false} viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current} onEndReached={() => setData([...data, ...animals])} onEndReachedThreshold={0.5} data={data} keyExtractor={(_, index) => `list_item${index}`} renderItem={({ item, index }) => { return <renderitem item="{item}" index="{index}" x="{x}"></renderitem>; }} /> <pagination paginationindex="{paginationIndex}"></pagination> </animated.flatlist></view> ); }; export default CustomCarousel; const styles = StyleSheet.create({ container: { flex: 1, }, buttonContainer: { justifyContent: 'center', alignItems: 'center', flexDirection: 'row', gap: 14, }, });
7. 結論
在本教程中,我們使用 React Native 的 FlatList 以及 Reanimated 建立了一個自訂輪播以實現流暢的動畫和插值。我們新增了具有動畫點、自動捲動功能的分頁系統,並確保使用者互動會暫停和恢復自動滾動功能。
使用這些元件,您可以擴展輪播以包含其他功能,例如動態內容、可點擊項目和更複雜的動畫。 React Native 與 Reanimated 的靈活性允許以最低的性能成本實現高度可自訂的輪播,這對於創建具有視覺吸引力的行動應用程式非常有用。
請隨意在您的專案中嘗試這一點,並自訂樣式和行為以滿足您的設計需求!
以上是使用 Reanimated 在 React Native 中建立具有自動滾動、無限循環、分頁功能的可自訂輪播的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

JavaScript框架的強大之處在於簡化開發、提升用戶體驗和應用性能。選擇框架時應考慮:1.項目規模和復雜度,2.團隊經驗,3.生態系統和社區支持。

引言我知道你可能會覺得奇怪,JavaScript、C 和瀏覽器之間到底有什麼關係?它們之間看似毫無關聯,但實際上,它們在現代網絡開發中扮演著非常重要的角色。今天我們就來深入探討一下這三者之間的緊密聯繫。通過這篇文章,你將了解到JavaScript如何在瀏覽器中運行,C 在瀏覽器引擎中的作用,以及它們如何共同推動網頁的渲染和交互。 JavaScript與瀏覽器的關係我們都知道,JavaScript是前端開發的核心語言,它直接在瀏覽器中運行,讓網頁變得生動有趣。你是否曾經想過,為什麼JavaScr

Node.js擅長於高效I/O,這在很大程度上要歸功於流。 流媒體匯總處理數據,避免內存過載 - 大型文件,網絡任務和實時應用程序的理想。將流與打字稿的類型安全結合起來創建POWE

Python和JavaScript在性能和效率方面的差異主要體現在:1)Python作為解釋型語言,運行速度較慢,但開發效率高,適合快速原型開發;2)JavaScript在瀏覽器中受限於單線程,但在Node.js中可利用多線程和異步I/O提升性能,兩者在實際項目中各有優勢。

JavaScript起源於1995年,由布蘭登·艾克創造,實現語言為C語言。 1.C語言為JavaScript提供了高性能和系統級編程能力。 2.JavaScript的內存管理和性能優化依賴於C語言。 3.C語言的跨平台特性幫助JavaScript在不同操作系統上高效運行。

JavaScript在瀏覽器和Node.js環境中運行,依賴JavaScript引擎解析和執行代碼。 1)解析階段生成抽象語法樹(AST);2)編譯階段將AST轉換為字節碼或機器碼;3)執行階段執行編譯後的代碼。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

WebStorm Mac版
好用的JavaScript開發工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

禪工作室 13.0.1
強大的PHP整合開發環境