React Framer Motion的AnimatePresence退出动画不生效问题求助
根因说明
你当前的AnimatePresence全部放在单个页面/组件内部,路由切换时整个页面组件会被直接卸载,AnimatePresence来不及触发退场动画就被销毁了,所以没有离场效果。
修改步骤
1. 把AnimatePresence移动到路由外层
找到你的根路由配置文件,将AnimatePresence包裹在路由切换容器的外层,以React Router v5为例:
import { AnimatePresence } from 'framer-motion' import { Switch, Route, useLocation } from 'react-router-dom' // 导入你的页面组件 import LGallery from './LGallery' import unItems from './unItems' function App() { const location = useLocation() return ( {/* AnimatePresence放在路由外层,添加exitBeforeEnter保证退场跑完再入场 */} <AnimatePresence exitBeforeEnter> {/* 给Switch添加唯一key,值为当前路由路径,触发AnimatePresence的状态检测 */} <Switch location={location} key={location.pathname}> <Route path="/work" exact component={LGallery} /> <Route path="/work/:id" component={unItems} /> {/* 其他路由规则 */} </Switch> </AnimatePresence> ) }
2. 删掉所有组件内部多余的AnimatePresence
AnimatePresence只需要包裹会被条件切换的父容器,你现在写在LGallery、WorkItems、unItems内部的AnimatePresence全部都是无效的,直接删除即可,保留内部的motion元素即可。
3. 修正key的错误用法
AnimatePresence本身不需要加key属性,只有它包裹的直接子元素需要加唯一稳定的key- 不要重复使用同一个
Items._id给同一层级的多个元素当key,避免状态检测异常
4. 可选:修复缓动值兼容问题
如果你用的是Framer Motion v2以上版本,内置的缓动函数已经没有anticipate这个值,替换为对应的贝塞尔曲线即可:
// 对应原来的anticipate缓动效果 ease: [.36, .66, .4, 1]
内容的提问来源于stack exchange,提问作者oORiggsOo
相关产品推荐
相关产品推荐

