React Native中Animated API控制SVG矩形高度失效问题求助
解决React Native中SVG矩形Animated动画失效的问题
嘿,我来帮你搞定这个SVG动画的问题!你遇到的情况其实挺常见的,主要是因为Animated API和react-native-svg的组件适配有几个容易踩的坑,咱们一步步来修复:
问题根源分析
- 错误的组件创建时机:你把
Animated.createAnimatedComponent(Rect)放在了render函数内部,这会导致每次组件渲染都生成一个全新的AnimatedRectangle组件类型,之前的动画状态直接丢失,自然没法正常工作。 - 原生驱动不兼容:React Native的
useNativeDriver动画只支持少数原生组件属性(比如transform、opacity),SVG的height属性不在支持列表里,强行开启原生驱动会导致动画失效。 - 组件适配问题:部分react-native-svg版本需要使用它内置的Animated包装组件,而非手动调用
createAnimatedComponent。
修复方案一:标准手动包装写法
先把Animated组件的创建移到组件外部,再关闭原生驱动:
import React, { Component } from 'react'; import { View, Animated } from 'react-native'; import Svg, { Rect } from 'react-native-svg'; // 把Animated组件创建移到组件外部,确保只生成一次 const AnimatedRectangle = Animated.createAnimatedComponent(Rect); class AnimatedSvgDemo extends Component { state = { height: new Animated.Value(5), }; componentDidMount() { Animated.timing(this.state.height, { toValue: 30, duration: 1000, // 增加时长方便观察动画效果 useNativeDriver: false, // SVG动画必须关闭原生驱动 }).start(); } render() { const { height } = this.state; return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Svg height="100" width="100" fill="#333"> <AnimatedRectangle x="0" y="0" width="4" height={height} fill="#333" /> <Rect x="10" y="0" width="4" height="7" fill="#333" /> <Rect x="20" y="0" width="4" height="7" fill="#333" /> </Svg> </View> ); } } export default AnimatedSvgDemo;
修复方案二:使用react-native-svg内置Animated组件
如果你的react-native-svg版本较新(v9+),它已经提供了预包装的Animated SVG组件,直接用更省心:
import React, { Component } from 'react'; import { View, Animated } from 'react-native'; import Svg, { Rect, AnimatedRect } from 'react-native-svg'; // 直接导入AnimatedRect class AnimatedSvgDemo extends Component { state = { height: new Animated.Value(5), }; componentDidMount() { Animated.timing(this.state.height, { toValue: 30, duration: 1000, useNativeDriver: false, }).start(); } render() { const { height } = this.state; return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Svg height="100" width="100" fill="#333"> <AnimatedRect x="0" y="0" width="4" height={height} fill="#333" /> <Rect x="10" y="0" width="4" height="7" fill="#333" /> <Rect x="20" y="0" width="4" height="7" fill="#333" /> </Svg> </View> ); } } export default AnimatedSvgDemo;
额外注意事项
如果你的react-native-svg版本太旧,可能不支持上述特性,建议先升级到最新版:
npm install react-native-svg@latest # 或者 yarn add react-native-svg@latest
内容的提问来源于stack exchange,提问作者Jaro
相关产品推荐
相关产品推荐

