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

React Native:如何实现淡出→状态变更→淡入的动画序列

解决React Native动画顺序问题:淡出→状态变更→淡入

问题分析

你当前代码里,setTextID会在动画启动前同步执行,而Animated.stagger是异步动画流程,导致文本先切换,再执行淡出淡入。要实现预期顺序,必须等淡出动画完全结束后再更新状态,接着启动淡入动画。

修改后的代码

import React, { useState } from 'react';
import { View, Text, Animated, TouchableOpacity } from 'react-native';

function App() {
  const fadeVal = useState(new Animated.Value(1))[0];
  const texts = ["first", "second", "third", "fourth"];
  const [textID, setTextID] = useState(0);
  
  const fadeIn = Animated.timing(fadeVal, {
    toValue: 1,
    duration: 500,
    useNativeDriver: true
  });
  
  const fadeOut = Animated.timing(fadeVal, {
    toValue: 0,
    duration: 500,
    useNativeDriver: true
  });

  function bothAtOnce() {
    // 先执行淡出动画,完成后更新状态再启动淡入
    fadeOut.start(() => {
      // 函数式更新避免闭包导致的状态偏差,同时实现文本循环切换
      setTextID(prevID => (prevID + 1) % texts.length);
      fadeIn.start();
    });
  }

  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <Animated.Text
        style={{
          width: 100,
          textAlign: 'center',
          justifyContent: 'center',
          opacity: fadeVal,
          backgroundColor: 'black',
          color: 'white'
        }}
      >
        {texts[textID]}
      </Animated.Text>
      <TouchableOpacity onPress={bothAtOnce}>
        <Text>Next</Text>
      </TouchableOpacity>
    </View>
  );
}

export default App;

关键修改点

  • 动画回调控制顺序:fadeOut.start()的回调函数会在淡出动画结束后触发,此时再更新文本状态,接着启动淡入,完全匹配你需要的执行顺序。
  • 函数式状态更新:用setTextID(prevID => ...)替代直接依赖textID的值,避免连续点击时的闭包问题,同时通过取模实现文本循环切换。
  • 移除Animated.stagger:手动通过回调串联动画比stagger更精准,能严格控制状态更新的时机。

补充说明

React Native没有类似CSS过渡的自动状态触发动画机制,通过Animated的回调函数串联动画与状态更新,是处理这类序列动画的标准方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:35:21