React Native中无法为SVG Path添加旋转动画,报‘undefined is not a function’错误
解决SVG Path旋转动画的"undefined is not a function"错误
错误原因分析
你的代码主要存在两个关键问题:
- 混用了Reanimated v1与v2的API:
Animated.Value、Animated.timing、Animated.loop是v1写法,和v2的useAnimatedPropshook不兼容,导致调用报错。 - SVG组件的transform属性格式错误:React Native View的transform用数组对象格式,但SVG Path的transform需要直接传入字符串格式。
修正后的代码
import React, { forwardRef, useState, useEffect } from 'react'; import { View, StyleSheet } from 'react-native'; import { Svg, Path } from 'react-native-svg'; import Animated, { useSharedValue, useAnimatedProps, withTiming, withRepeat, Easing } from 'react-native-reanimated'; const AnimatedPath = Animated.createAnimatedComponent(Path); const Shape = forwardRef((props, ref) => { const [currentPath, setCurrentPath] = useState([]); // 改用Reanimated v2+的useSharedValue管理动画状态 const rotation = useSharedValue(0); const startRotation = () => { // 用v2的withRepeat + withTiming实现无限循环动画 rotation.value = withRepeat( withTiming(1, { duration: 1000, easing: Easing.linear, }), -1, // -1表示无限重复 false ); }; // 组件挂载后自动启动动画 useEffect(() => { startRotation(); }, []); const animatedProps = useAnimatedProps(() => { // 生成SVG兼容的transform字符串 const rotateAngle = rotation.value * 360; return { transform: `rotate(${rotateAngle} 0 0)` }; }); return ( <View style={styles.container}> <Svg style={styles.svg} height="100%" width="100%"> <AnimatedPath d={currentPath.join('')} stroke={props.colour} fill={'transparent'} strokeWidth={2} strokeLinejoin={'round'} strokeLinecap={'round'} animatedProps={animatedProps} onPress={() => {}} /> </Svg> </View> ); }); // 补充缺失的样式定义 const styles = StyleSheet.create({ container: { flex: 1, }, svg: { flex: 1, }, }); export default Shape;
关键修正说明
- 状态管理替换:用
useSharedValue替代Animated.Value,适配Reanimated v2+的hook体系。 - 动画API升级:用
withRepeat和withTiming替代旧版的Animated.loop与Animated.timing,符合函数式动画规范。 - transform格式调整:直接返回SVG支持的字符串格式transform属性,而非React Native View的数组对象格式。
- 自动启动动画:通过
useEffect在组件挂载后触发动画,避免手动调用遗漏。
内容的提问来源于stack exchange,提问作者user2001154
相关产品推荐
相关产品推荐

