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

如何实现React Native中图片的循环脉冲加载动画?

问题分析与修复方案

你的代码存在几个关键问题,导致无法实现无限循环的脉冲缩放效果:

  • Animated.loop 仅包裹了第一个动画,回调内的第二个动画不在循环范围内,只会执行一次就停止
  • 第一个动画的 toValue 和初始值均为0,没有任何动画变化
  • 插值的输出范围设置不符合需求,当前是从1缩到0,而非交替缩放的脉冲效果

修复后的简洁实现

import { useRef, useEffect } from 'react';
import { Animated } from 'react-native';

// 假设Logo已正确导入
export default function PulseLoader() {
  const scaleValue = useRef(new Animated.Value(1)).current;

  useEffect(() => {
    const pulseAnimation = Animated.timing(scaleValue, {
      toValue: 1.2, // 放大到原尺寸的1.2倍
      duration: 800,
      useNativeDriver: true,
      autoreverse: true, // 动画结束后自动反向执行
      repeat: -1 // 无限重复(-1表示无限次)
    });

    pulseAnimation.start();

    // 组件卸载时停止动画,避免内存泄漏
    return () => pulseAnimation.stop();
  }, []);

  return (
    <Animated.Image
      style={{
        width: 165,
        height: 75,
        transform: [{ scale: scaleValue }]
      }}
      source={Logo}
    />
  );
}

手动控制正反动画的实现方式

如果你更倾向于手动管理正向和反向动画流程,可以用 Animated.loop 包裹 Animated.sequence:

useEffect(() => {
  const pulseSequence = Animated.sequence([
    Animated.timing(scaleValue, {
      toValue: 1.2,
      duration: 800,
      useNativeDriver: true
    }),
    Animated.timing(scaleValue, {
      toValue: 1,
      duration: 800,
      useNativeDriver: true
    })
  ]);

  const loopAnimation = Animated.loop(pulseSequence);
  loopAnimation.start();

  return () => loopAnimation.stop();
}, []);

核心说明

  • autoreverse: true + repeat: -1 是实现无限脉冲最简洁的方案,无需手动编写反向逻辑
  • 初始值设为1(原尺寸),toValue 设为大于1的数值实现放大,反向时自动还原
  • 组件卸载时必须停止动画,防止内存泄漏

内容的提问来源于stack exchange,提问作者julziemoon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:07:30