在 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字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

因此,在這裡,您準備好了解所有稱為Ajax的東西。但是,到底是什麼? AJAX一詞是指用於創建動態,交互式Web內容的一系列寬鬆的技術。 Ajax一詞,最初由Jesse J創造

10款趣味橫生的jQuery遊戲插件,讓您的網站更具吸引力,提升用戶粘性!雖然Flash仍然是開發休閒網頁遊戲的最佳軟件,但jQuery也能創造出令人驚喜的效果,雖然無法與純動作Flash遊戲媲美,但在某些情況下,您也能在瀏覽器中獲得意想不到的樂趣。 jQuery井字棋遊戲 遊戲編程的“Hello world”,現在有了jQuery版本。 源碼 jQuery瘋狂填詞遊戲 這是一個填空遊戲,由於不知道單詞的上下文,可能會產生一些古怪的結果。 源碼 jQuery掃雷遊戲

本教程演示瞭如何使用jQuery創建迷人的視差背景效果。 我們將構建一個帶有分層圖像的標題橫幅,從而創造出令人驚嘆的視覺深度。 更新的插件可與JQuery 1.6.4及更高版本一起使用。 下載

本文討論了在瀏覽器中優化JavaScript性能的策略,重點是減少執行時間並最大程度地減少對頁面負載速度的影響。

本文演示瞭如何使用jQuery和ajax自動每5秒自動刷新DIV的內容。 該示例從RSS提要中獲取並顯示了最新的博客文章以及最後的刷新時間戳。 加載圖像是選擇

Matter.js是一個用JavaScript編寫的2D剛體物理引擎。此庫可以幫助您輕鬆地在瀏覽器中模擬2D物理。它提供了許多功能,例如創建剛體並為其分配質量、面積或密度等物理屬性的能力。您還可以模擬不同類型的碰撞和力,例如重力摩擦力。 Matter.js支持所有主流瀏覽器。此外,它也適用於移動設備,因為它可以檢測觸摸並具有響應能力。所有這些功能都使其值得您投入時間學習如何使用該引擎,因為這樣您就可以輕鬆創建基於物理的2D遊戲或模擬。在本教程中,我將介紹此庫的基礎知識,包括其安裝和用法,並提供一


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

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

Atom編輯器mac版下載
最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver Mac版
視覺化網頁開發工具