網站搜尋

reactjs - Framer-motion 退出動畫未觸發


https://codesandbox.io/s/framer-motion-not-working-id46n?file=/src/Notifications.tsx


如你在這個 GIF 中所見,通知在從 DOM 中移除時不會執行退出動畫。(它們分別在生成後 6 秒移除)為什麼會這樣?

我已經做了其他答案中提到的所有事情,例如:

  1. 為每個通知子項添加唯一鍵
  2. <Routes location={location} key={location.pathname}>
  3. 等等

為什麼它不起作用?

目標:讓通知在被移除時播放一些退出動畫(即在指定的通知持續時間之後)

答案#1

退出的元素需要是 <AnimatePresence> 標籤的 直接子元素。

你的沙盒在這裡無法運行,所以我無法驗證這個解決方案,但如果你把結構從這個改變,它應該可以工作:

<AnimatePresence>
  <NotificationContext>
    <div id="notificationCenter">
      <motion.div key={notification.id} />
    </div>
  </NotificationContext>
</AnimatePresence>

到這個:

<NotificationContext>
  <div id="notificationCenter">
    <AnimatePresence>
      <motion.div key={notification.id} />
    </AnimatePresence>
  </div>
<NotificationContext>