如何使用react-native-reanimated实现expo-linear-gradient的颜色动画?
问题解答
你遇到的问题确实和animatedProps的使用有关——expo-linear-gradient的colors是JS层的组件参数,并非原生视图直接暴露的可动画属性,所以useAnimatedProps无法直接驱动它的变化,导致动画不生效。
下面提供两种可行的解决方案:
方案一:使用Animated.View结合原生驱动的渐变动画(推荐)
利用useAnimatedStyle生成动态渐变背景,基于原生视图属性驱动,性能更优:
import * as React from 'react'; import { View, Button } from 'react-native'; import Animated, { interpolateColor, useAnimatedStyle, useSharedValue, withTiming, } from 'react-native-reanimated'; export default function App() { const colorsValue = useSharedValue(1); const animatedStyle = useAnimatedStyle(() => { const startColor = interpolateColor(colorsValue.value, [0, 1], ['#FFFFFF', '#000000']); const endColor = interpolateColor(colorsValue.value, [0, 1], ['#FFFFFF', '#00ff00']); return { backgroundImage: `linear-gradient(to bottom, ${startColor}, ${endColor})`, }; }); return ( <View> <Animated.View style={[ { height: 400, width: '100%' }, animatedStyle ]} /> <Button title="Change colors" onPress={() => (colorsValue.value = withTiming(0, { duration: 2000 }))} /> </View> ); }
方案二:结合useDerivedValue适配expo-linear-gradient
如果必须使用expo-linear-gradient,可以通过useDerivedValue监听共享值变化,同步更新组件的colors参数(此方案基于JS线程驱动,性能略逊于方案一):
import * as React from 'react'; import { View, Button } from 'react-native'; import Animated, { interpolateColor, useDerivedValue, useSharedValue, withTiming, } from 'react-native-reanimated'; import { LinearGradient } from 'expo-linear-gradient'; export default function App() { const colorsValue = useSharedValue(1); const [colors, setColors] = React.useState(['#000000', '#00ff00']); useDerivedValue(() => { const newColors = [ interpolateColor(colorsValue.value, [0, 1], ['#FFFFFF', '#000000']), interpolateColor(colorsValue.value, [0, 1], ['#FFFFFF', '#00ff00']), ]; setColors(newColors); }, [colorsValue]); return ( <View> <LinearGradient colors={colors} style={{ height: 400, width: '100%' }} /> <Button title="Change colors" onPress={() => (colorsValue.value = withTiming(0, { duration: 2000 }))} /> </View> ); }
内容的提问来源于stack exchange,提问作者RaideR
相关产品推荐
相关产品推荐

