React Native Reanimated interpolateColor赋值stroke报错求助
问题原因及解决方案
这个报错的核心原因是:React Native Reanimated 在通过useAnimatedProps传递 react-native-svg 的颜色属性时,不接受字符串格式的颜色值。
直接在AnimatedCircle上写stroke="rgb(247, 30, 43)"正常,是因为 react-native-svg 本身会自动解析字符串格式的颜色;但通过useAnimatedProps传递时,Reanimated 内部会期望接收一个符合原生端要求的颜色对象(带r/g/b/a字段的ReadableMap结构),而你返回的字符串会被它当作ReadableMap去强制转换,所以抛出了类型转换异常。
解决方法有两种:
方法1:用Reanimated的color函数包装插值结果
Reanimated提供了color工具函数,可以把字符串格式的颜色转换成它能识别的颜色对象,直接用这个函数包裹interpolateColor的返回值即可:
import { useAnimatedProps, interpolateColor, color } from 'react-native-reanimated'; import Animated, { Circle } from 'react-native-svg'; const AnimatedCircle = Animated.createAnimatedComponent(Circle); // 省略其他代码 const animatedProps = useAnimatedProps(() => { const dynamicColor = interpolateColor( percentage.value, [0, 100], ['rgb(200, 200, 200)', 'rgb(247, 30, 43)'] ); return { stroke: color(dynamicColor), }; });
方法2:直接插值生成RGB数值,返回颜色对象
跳过字符串颜色,直接对RGB三个通道分别插值,返回包含r/g/b字段的对象:
import { useAnimatedProps, interpolate } from 'react-native-reanimated'; import Animated, { Circle } from 'react-native-svg'; const AnimatedCircle = Animated.createAnimatedComponent(Circle); // 省略其他代码 const animatedProps = useAnimatedProps(() => { const r = interpolate(percentage.value, [0, 100], [200, 247]); const g = interpolate(percentage.value, [0, 100], [200, 30]); const b = interpolate(percentage.value, [0, 100], [200, 43]); return { stroke: { r, g, b }, }; });
额外注意
确保你的react-native-reanimated和react-native-svg版本兼容,比如Reanimated 2.x及以上搭配RN-SVG 12.x及以上,版本不匹配也可能触发这类属性传递的异常。
内容的提问来源于stack exchange,提问作者Blue
相关产品推荐
相关产品推荐

