react-native - 反应原生动画不透明度和位置
问题描述
我想在我的应用程序中创建一个动画,其中包括转换视图的位置和不透明度。现在,我所拥有的只是转换视图,我已经这样做了:
const fadeAnim = useRef(new Animated.Value(0)).current
useEffect(()=> {
Animated.timing(
fadeAnim,
{
toValue: 1,
duration: 1000,
useNativeDriver: true,
delay: 2000,
}
).start();
}, [fadeAnim])
<Animated.View style={{
opacity: fadeAnim
}}>
{content}
</Animated.View>
我怎样才能编辑它来转换位置,然后几秒钟后,我想隐藏这个容器。
解决方案
我建议对动画有一个更通用的功能,这样你就可以把它放在一个单独的文件中,并在你需要的任何地方使用它。像这样的东西:
const opacityRef = useRef(new Animated.Value(0)).current
const translateRef = useRef(new Animated.Value(0)).current
const initialX = 0
const finalX = 100 // these values should be put inside constants so you'll have to change them if you need to only in one place
// this is a general animation function, you can use it for opacity, translations, rotations
const animateView = (toValue: number, animatedRef: Animated.Value, duration: number, delay: number) => {
return Animated.timing(
animatedRef,
{
toValue,
duration,
useNativeDriver: true,
delay,
}
)
}
// you can implement sequences of animations or even parallel if you need to (take a look at the docs)
useEffect(()=> {
Animated.sequence([
animateView(finalX, translateRef, 1000, 0),
animateView(initialX, translateRef, 1000, 0),
animateView(0, opacityRef, 1000, 2000),
animateView(1, opacityRef, 1000, 0),
]).start()
}, [])
return (
<Animated.View style={{
backgroundColor: 'red',
width: 100,
height: 100,
left: 0,
opacity: opacityRef,
transform: [{
translateX: translateRef
}]
}}/>
)
推荐阅读
- python - 删除列表周围的方括号和撇号
- c# - MPMediaPickerController-> MPmediaitem -> NSDATA (xamarin, c#, ios)
- c - 如何从文本文件中读取并使用结构将其加载到内存中?
- file - 在 COBOL 中,如何将符号 comp-3 值与符号一起转换为可读格式
- reactjs - ReactJS:使用上一个和下一个按钮更改当前显示的图像
- apache-spark - Spark我可以在执行textFile时手动指定分区数吗
- python - 加载 Keras 模型 KeyError:'weighted_metrics'
- android - 在 Android 应用程序中嵌入 YouTube 直播
- csv - 将csv科学记数法转换为unix中的数字
- javascript - 如何从 wikipedia api 获取前 100 个字符