React路由器dom(v6)与Framer Motion(v4)



我正试图将我的react路由器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

";首字母";以及";动画化";工作正常,但退出被忽略,并立即跳到相关页面(而不是先设置动画(。

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

感谢您的帮助。

您需要向Routes提供keylocation道具,如下所示:

动画路线.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>
);
}

正在工作的代码沙盒。

最新更新