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

React Native状态变更时淡入动画失效问题求助

React Native 淡入动画未生效问题排查与修复

你的动画仅在第一次数字变化时生效,后续无反应,核心问题在于:fadeAnim在首次动画结束后停留在值1,后续触发useEffect时,Animated.timing的目标值还是1,没有数值变化,因此动画不会执行。此外,当前逻辑未处理定时器的重复创建问题,可能引发额外异常。

修复方案

  • 重置动画初始值:每次执行淡入前,先将fadeAnim重置为0,再启动到1的动画
  • 清理定时器:组件卸载或重新触发时清理旧定时器,避免内存泄漏与重复执行
  • 优化动画触发逻辑:确保每次数字更新时,动画能完整执行淡入流程

修改后代码

import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Button, Animated } from 'react-native';

const BoxWithRandomNumber = () => {
  const [number, setNumber] = useState(1);
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const intervalRef = useRef(null); // 存储定时器引用

  useEffect(() => {
    // 先立即重置动画到0,再执行淡入到1的动画
    Animated.sequence([
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 0,
        useNativeDriver: true,
      }),
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 1000,
        useNativeDriver: true,
      })
    ]).start();

    // 组件卸载时清理定时器
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [number]);

  const generateRandom = () => {
    let c = 0;
    // 清理旧定时器,避免重复触发
    if (intervalRef.current) clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      setNumber(Math.floor(Math.random() * 10));
      if (++c === 5) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    }, 1500);
  };

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>  
      <Animated.Text 
        style={{ 
          fontSize: 36, 
          fontWeight: 'bold', 
          color: '#ecf0f1',
          opacity: fadeAnim, 
        }}
      >
        {number}
      </Animated.Text>
      <Button title="Start" onPress={generateRandom} />
    </View>
  );
};

export default BoxWithRandomNumber;

关键修改说明

  1. 使用Animated.sequence组合两个动画:先立即重置透明度为0,再执行1秒的淡入到1的动画,确保每次数字更新都有完整的淡入效果
  2. 新增intervalRef管理定时器,在重新点击Start或组件卸载时清理旧定时器,避免多个定时器同时运行
  3. 给useEffect添加清理函数,防止组件卸载后定时器继续运行引发内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:55:32