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

Reanimated v3条件淡入淡出动画失效问题排查

React Native Reanimated v3 条件渲染淡入淡出动画失效问题修复

你的代码失效的核心原因有两个:

  1. 直接用三元表达式切换组件会导致旧组件被立即卸载,Reanimated的exiting动画根本没机会执行;新组件也会被直接挂载,entering动画无法正常触发——React的条件渲染不会等待动画完成再替换组件。
  2. layout属性是用来处理组件内部布局变化的动画(比如尺寸、位置改变),不是用来处理组件挂载/卸载的,这里属于误用。

修复方案

使用Reanimated v3提供的AnimatedSwitcher组件,它专门用来处理子组件切换时的进入/退出动画,会自动等待旧组件的退出动画完成后再卸载,同时触发新组件的进入动画。

修改后的代码如下:

import { AnimatedSwitcher } from 'react-native-reanimated';

const MyComponent = () => {
  const [didLoad, setDidLoad] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => {
      setDidLoad(prev => !prev);
    }, 3000);

    return () => clearInterval(interval);
  }, []);

  return (
    <AnimatedSwitcher>
      {didLoad ? (
        <Animated.View
          key="skeleton"
          entering={FadeIn}
          exiting={FadeOut}
        >
          <SkeletonPlaceholder borderRadius="4">
            <SkeletonPlaceholder.Item alignItems="center" flexDirection="row">
              <SkeletonPlaceholder.Item
                borderRadius="50"
                height={20}
                width={20}
              />
              <SkeletonPlaceholder.Item marginLeft={20}>
                <SkeletonPlaceholder.Item height={25} width={120} />
                <SkeletonPlaceholder.Item
                  height={25}
                  marginTop={6}
                  width={80}
                />
              </SkeletonPlaceholder.Item>
            </SkeletonPlaceholder.Item>
          </SkeletonPlaceholder>
        </Animated.View>
      ) : (
        <Animated.View
          key="icons"
          entering={FadeIn}
          exiting={FadeOut}
        >
          <View style={tw`flex-row items-center gap-2`}>
            <Icon name="chevron-right" />
            <Icon name="chevron-left" />
            <Icon name="map" />
            <Icon name="home" />
          </View>
        </Animated.View>
      )}
    </AnimatedSwitcher>
  );
};

关键改动说明

  • 用AnimatedSwitcher包裹两个切换的组件,它会管理组件的卸载时机,等待退出动画完成。
  • 给每个子组件添加唯一的key,这是React识别组件身份的关键,AnimatedSwitcher依赖key来判断是否需要触发切换动画。
  • 移除了无用的layout属性,专注于挂载/卸载的entering/exiting动画。

如果需要自定义动画时长或延迟,可以直接在FadeIn/FadeOut上链式调用配置,比如:

entering={FadeIn.duration(300).delay(100)}
exiting={FadeOut.duration(300)}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:52:47