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

使用Framer Motion的AnimatePresence切换组件时退出动画失效原因咨询

问题原因及解决思路
  • 核心原因:直接通过条件渲染(如{isShow && <MyComponent />})切换组件时,React会立即卸载不满足条件的组件,DOM元素被瞬间移除,导致CSS过渡/动画没有足够时间执行。

  • 关键原理:退出动画需要组件在DOM中保留足够时长,直到动画完成后再被移除。普通条件渲染不具备这种延迟卸载的机制。

  • 解决方法:使用专门的过渡管理组件(如React Transition Group的CSSTransition),它会:

    1. 在组件卸载时添加退出动画类名
    2. 等待动画时长结束后,再真正移除DOM元素
    3. 配合CSS定义exit和exit-active状态的过渡样式

举个简化的代码示例:

import { CSSTransition } from 'react-transition-group';
import { useState } from 'react';

function App() {
  const [showComponent, setShowComponent] = useState(true);

  return (
    <div>
      <button onClick={() => setShowComponent(!showComponent)}>切换</button>
      <CSSTransition
        in={showComponent}
        timeout={3000}
        classNames="fade"
        unmountOnExit
      >
        <div className="box">我有退出动画</div>
      </CSSTransition>
    </div>
  );
}

对应的CSS:

.fade-enter { opacity: 0; }
.fade-enter-active { opacity: 1; transition: opacity 3000ms; }
.fade-exit { opacity: 1; }
.fade-exit-active { opacity: 0; transition: opacity 3000ms; }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:17:31