You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中Animated API控制SVG矩形高度失效问题求助

解决React Native中SVG矩形Animated动画失效的问题

嘿,我来帮你搞定这个SVG动画的问题!你遇到的情况其实挺常见的,主要是因为Animated API和react-native-svg的组件适配有几个容易踩的坑,咱们一步步来修复:

问题根源分析

  1. 错误的组件创建时机:你把Animated.createAnimatedComponent(Rect)放在了render函数内部,这会导致每次组件渲染都生成一个全新的AnimatedRectangle组件类型,之前的动画状态直接丢失,自然没法正常工作。
  2. 原生驱动不兼容:React Native的useNativeDriver动画只支持少数原生组件属性(比如transform、opacity),SVG的height属性不在支持列表里,强行开启原生驱动会导致动画失效。
  3. 组件适配问题:部分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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:28:34