如何使用React Native Reanimated 2实现多个组件的透明度动画
问题原因
同一个useAnimatedStyle返回的动画样式对象不支持复用到多个Animated组件上。Reanimated 2内部会对动画样式和绑定的Animated组件做一对一关联绑定,重复使用同一个动画样式实例时,只有最后一个绑定的组件会响应动画值更新。
解决方案
方案1:为每个组件单独创建动画样式
所有动画样式可以共用同一个sharedValue,只需要单独调用useAnimatedStyle生成每个组件对应的动画样式即可:
const Baby = () => { const signUpOpacity = useSharedValue(0.1); // 第一个方块的动画样式 const firstBoxStyle = useAnimatedStyle(() => { return { opacity: withTiming(signUpOpacity.value, { duration: 300 }), }; }); // 第二个方块的动画样式 const secondBoxStyle = useAnimatedStyle(() => { return { opacity: withTiming(signUpOpacity.value, { duration: 300 }), }; }); return( <View> <TouchableOpacity onPress={() => (signUpOpacity.value = 1)}> <Text style={styles.welcomeText}>Welcome</Text> </TouchableOpacity> <Animated.View style={[{ width: 50, height: 50, backgroundColor: 'red', marginTop: 20, }, firstBoxStyle]} /> <Animated.View style={[{ width: 50, height: 50, backgroundColor: 'red', marginTop: 20, }, secondBoxStyle]} /> </View> ) }
方案2:封装独立动画组件(适合多组件场景)
如果需要应用动画的组件数量多,建议封装成独立子组件,每个组件内部维护自己的动画样式,外部只需要传入共享的动画值即可:
// 封装可复用的动画方块组件 const AnimatedBox = ({ opacitySharedValue }) => { const animatedStyle = useAnimatedStyle(() => { return { opacity: withTiming(opacitySharedValue.value, { duration: 300 }), }; }); return ( <Animated.View style={[{ width: 50, height: 50, backgroundColor: 'red', marginTop: 20, }, animatedStyle]} /> ) } const Baby = () => { const signUpOpacity = useSharedValue(0.1); return( <View> <TouchableOpacity onPress={() => (signUpOpacity.value = 1)}> <Text style={styles.welcomeText}>Welcome</Text> </TouchableOpacity> <AnimatedBox opacitySharedValue={signUpOpacity} /> <AnimatedBox opacitySharedValue={signUpOpacity} /> </View> ) }
内容的提问来源于stack exchange,提问作者Kerry
相关产品推荐
相关产品推荐

