react native中使用Animated实现三张图片动态旋转效果
warning:
这篇文章距离上次修改已过205天,其中的内容可能已经有所变动。
import React, { useRef, useEffect } from 'react';
import { Animated, Image, StyleSheet, Text, View } from 'react-native';
const ImageRotator = () => {
const fadeAnim = useRef(new Animated.Value(1)).current;
const images = ['image1', 'image2', 'image3'];
const [activeImage, setActiveImage] = React.useState(0);
useEffect(() => {
Animated.sequence([
Animated.timing(fadeAnim, {
toValue: 0,
duration: 1000,
useNativeDriver: true,
}),
Animated.timing(fadeAnim, {
toValue: 1,
duration: 1000,
delay: 3000,
useNativeDriver: true,
}),
]).start(() => setActiveImage((activeImage + 1) % images.length));
}, [fadeAnim, activeImage]);
return (
<Animated.Image
style={[styles.image, {opacity: fadeAnim}]}
source={{uri: images[activeImage]}}
/>
);
};
const styles = StyleSheet.create({
image: {
width: 300,
height: 300,
},
});
export default ImageRotator;
这段代码使用了React Native的Animated API来创建一个动态的图片轮播器。它使用了Animated.Image组件和Animated.timing函数来实现图片的淡入淡出效果,并通过useEffect钩子来管理动画的循环。代码简洁,易于理解和学习。
评论已关闭