【问题标题】:Frame Motion exit animation not working with Next.JS帧运动退出动画不适用于 Next.JS
【发布时间】:2021-12-12 09:44:55
【问题描述】:

我正在学习 Next.JS 和 Framer Motion 以提高我的技能。因此,我正在尝试进行淡入/淡出页面转换,但无法使其正常工作,也无法弄清楚原因。

淡入动画效果很好,但是,当我单击(更改当前页面)时,淡出没有显示...

这是我的代码:

/shared/layout.js

export default function Layout({ children }){
    return (
        <>
            <Head>
                <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
            </Head>
            <Header />
            <main>
                <AnimatePresence exitBeforeEnter>
                    { children }
                </AnimatePresence>
            </main>
        </>
    )
}

/pages/_app.js

function MyApp({ Component, pageProps }) {
  return (
      <Layout>
        <Component {...pageProps} />
      </Layout>
  )
}

export default MyApp

/pages/index.js

export default function Home(){
  return (
    <motion.div id="home" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: .5 }}>
      <Head>
        <title>Home</title>
      </Head>
      
      // Bla bla bla goes here
    </motion.div>
  );
}

/pages/about.js

export default function About(){
  return (
    <motion.div id="about" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: .5 }}>
      <Head>
        <title>About</title>
      </Head>
      
      // Bla bla bla goes here
    </motion.div>
  );
}

/pages/contact.js

export default function Contact(){
  return (
    <motion.div id="home" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: .5 }}>
      <Head>
        <title>Contact</title>
      </Head>
      
      // Bla bla bla goes here
    </motion.div>
  );
}

在搜索时,我发现很多人说“目前,如果不添加初始状态,退出动画将不起作用”,但我在所有 motion.div 组件上都使用了 initial prop,并且我的 AnimatePresence 位于正确的位置(我认为),作为所有 motion.div 组件的父级。

有人可以帮我吗?

谢谢!

【问题讨论】:

    标签: javascript animation next.js transition framer-motion


    【解决方案1】:

    我通过在 _app 中使用以下代码实现了同样的效果

    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      key={router.asPath}
      transition={{
        duration: 0.3,
        ease: 'easeInOut',
        type: 'tween',
      }}
    >
      <Component {...pageProps} />
    </motion.div>
    

    【讨论】:

    • 这是个好主意...但是,我在这里尝试了您的方法,但对我没有用。淡入动画在页面加载后运行,尝试导航时没有任何反应......我想要页面之间的淡入/淡出过渡......对不起
    • 您一定是以错误的方式实现它。也许如果您添加更多代码,我将能够为您提供帮助
    • 我刚刚将我的代码上传到了我的 GitHub...你能检查一下并帮助我吗? NextJS Project谢谢!!
    • 将您问题的代码更新到最新版本(您尝试过的)。然后尝试删除 AnimatePresence 并使用我发布的代码来代替
    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 2023-01-16
    • 2015-01-15
    • 1970-01-01
    • 2015-08-25
    • 2022-11-24
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多