React-router-dom (v6) 与 Framer Motion (v4)

React-router-dom (v6) with Framer Motion (v4)

我正在尝试将我的 react-router-dom 更新到 v6,但它似乎导致了成帧器动画 AnimatePresence 的问题,特别是退出过渡。

在App.js中:

import { Routes, Route } from "react-router-dom";
import {AnimatePresence} from "framer-motion";  

import Home from "./Components/Home";
import About from "./Components/About";
function App() {
  return (
    <div className="App">

      {/* globals such as header will go here  */}

      <AnimatePresence exitBeforeEnter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="about" element={<About />} />
        </Routes>
      </AnimatePresence>
    </div>
  );
}

export default App;

然后在我的 About/Home 组件中我有:

import {Link} from "react-router-dom";
import {motion} from "framer-motion";  

    function About() {
    
        const pageMotion = {
            initial: {opacity: 0, x: 0},
            animate: {opacity: 1, x: 50, transition: {duration: 2}},
            exit: {opacity: 0, x:0, transition: {duration: 2}}
        };
    
        return (
            <div className="about">
                <motion.div initial="initial" animate="animate" exit="exit" variants={pageMotion}>about page</motion.div>
                <Link to="/">Go to home page</Link>
            </div>
        )
    }
    
    export default About

“初始”和“动画”工作正常,但忽略退出,并立即跳转到相关页面(而不是先动画)。

注意:我还不得不降级到 framer-motion v4,因为 v5 不适用于 Create-react-app。

感谢任何帮助。

您需要像这样向 Routes 提供 keylocation 道具:

AnimatedRoutes.js

const AnimatedRoutes = () => {
  const location = useLocation();

  return (
    <AnimatePresence exitBeforeEnter>
      <Routes location={location} key={location.pathname}>
        <Route path="/" element={<Home />} />
        <Route path="about" element={<About />} />
      </Routes>
    </AnimatePresence>
  );
};

并且由于调用 useLocation 的组件必须包装在 BrowserRouter 中:

App.js

function App() {
  return (
    <BrowserRouter>
      <AnimatedRoutes />
    </BrowserRouter>
  );
}

Working CodeSandbox.