带Framer Motion(V4)的REACT-ROUTER-DOM(V6)

我正在尝试将我的REACTION-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;

然后在我的关于/主页组件中:

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

首字母&q;和动画&q;可以正常工作,但退出会被忽略,并且会立即跳到相关页面(而不是首先动画)。

注意:我还不得不降级到Framer-Motion v4,因为v5不能与Create-Reaction-app一起使用。

感谢任何帮助。


解决方案

您需要向Routeskeylocation提供这样的道具:

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的组件必须包装在浏览器路由器中:

App.js

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

Working CodeSandbox。

相关文章