Framer Motion退出动画失效求助:初始与入场动画正常
解决Framer Motion v7.x退出动画失效问题
核心问题原因
你的代码中退出动画失效的关键原因是未给条件渲染的motion元素添加唯一key属性。AnimatePresence依赖key来精准追踪组件的挂载与卸载状态,缺少唯一key会导致它无法识别元素的移除操作,进而无法触发退出动画。
修复方案
为每个条件渲染的motion元素添加唯一的key属性,确保AnimatePresence能正确感知元素的状态变化。
修改后的代码示例
return ( <> <AnimatePresence> {props.profile && ( <motion.div key="modal-overlay" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.3 }} className={css.overlay} ></motion.div> )} </AnimatePresence> <AnimatePresence> {props.profile && ( <motion.div key="profile-modal" className={css.profile} initial={{ opacity: 0, top: "-200px", transform: "translate(-50%,-50%)", }} animate={{ opacity: 1, top: "50%", }} exit={{ opacity: 0, top: "-200px" }} transition={{ duration: 0.5 }} > some code </motion.div> )} </AnimatePresence> </> )
额外优化建议
如果遮罩层和弹窗是关联的联动组件,可以将它们放在同一个AnimatePresence容器下,保证两个元素的退出动画同步触发:
<AnimatePresence> {props.profile && ( <> <motion.div key="modal-overlay" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.3 }} className={css.overlay} ></motion.div> <motion.div key="profile-modal" className={css.profile} initial={{ opacity: 0, top: "-200px", transform: "translate(-50%,-50%)", }} animate={{ opacity: 1, top: "50%", }} exit={{ opacity: 0, top: "-200px" }} transition={{ duration: 0.5 }} > some code </motion.div> </> )} </AnimatePresence>
内容的提问来源于stack exchange,提问作者Mr A
相关产品推荐
相关产品推荐

