如何使用 reanimated v2 通过过渡更改背景颜色

问题描述

我是 react-native-reanimated 的新手。我正在尝试根据状态更改 backgorundCOlor。现在我有这样的代码

const [visible,setVisible] = useState<boolean>(true)
const backgroundColor = useSharedValue(0);
const backgroundColorStyle = useDerivedValue(() => interpolateColor(backgroundColor.value,[0,1],['transparent','rgba(0,.5)']) )

const backgroundInterpolate = useAnimatedStyle(() => ({
    backgroundColor: backgroundColorStyle.value
}),[])

  .... 

<Animated.View style={[{height: '65%'},backgroundInterpolate]}> 
   ....

</Animated.View>

所以用这个代码我得到了这样的错误

error message

也许我把它弄得太复杂了,这样简单的任务,比如随着过渡而改变背景颜色。无论如何,我都会向你寻求帮助,因为我被堆积如山。

解决方法

我会通过将共享值本身设为布尔值来简化它,然后使用它来控制背景颜色

const backgroundColor = useSharedValue(false) 

const backgroundInterpolate = useAnimatedStyle(() => ({
    backgroundColor: backgroundColor.value ? 'transparent': 'rgba(0,0),.5)',}),[])