当你通过路由更改页面时,React CSSTransition



我正在使用CSSTransition,它与组件配合使用非常出色:

<CSSTransition timeout={330} in={state.isPopupOpen} classNames="popup" unmountOnExit>
<MyComponent />
</CSSTransition>

我想知道当我按Route打开/关闭页面时,我是否可以使用CSSTransition进行很好的过渡:

<BrowserRouter>
<Switch>
<Route path="/page1">
<CSSTransition timeout={330} in={state.isPageOpen} classNames="page" unmountOnExit>
<Page1 />
</CSSTransition>
</Route>
<Route path="/page2">
<Page2 />
</Route>
<Switch>
</BrowserRouter>
<Link to="/page1">Link example</Link>

我尝试了一下,但没有成功。以这种方式使用CSSTransition是不可能的吗?您还有其他类似的解决方案吗?

感谢@xadm的评论,我在 https://css-tricks.com/animating-between-views-in-react/上测试了一个有用的解决方案

然而,在 React Router v6 中,我发现了一个更简单的解决方案,它有一个叫做 Framer Motion (https://www.framer.com/motion/( 的不同库。

相同的结果,在一段代码中总结的工作量更少

import { AnimatePresence } from 'framer-motion'
import { BrowserRouter, Routes, Route, Link, useLocation } from "react-router-dom";
import { motion } from 'framer-motion'
const PageTransition = (props) => {
return (
<motion.div
{...props}
initial={{ opacity: 0, x: '50vw' }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: '-50vw' }}
style={{ position: 'fixed', top: 0, left: 0, width: '100%', height: '100%' }}
transition={{ type: 'tween', duration: .3 }}
>
{props.children}
</motion.div>
)
}
const Page1 = (props) => {
return (
<PageTransition>
<h3>Page 1</h3>
<Link to="/page2">Go to Page 2</Link>
</PageTransition>
);
}
const Page2 = (props) => {
return (
<PageTransition>
<h3>Page 2</h3>
<Link to="/">Go to Page 1</Link>
</PageTransition>
);
}
const AnimatedRoutes = () => {
const location = useLocation();
return (
<AnimatePresence exitBeforeEnter>
<Routes location={location} key={location.pathname}>
<Route path="/" element={<Page1 />} />
<Route path="/page2" element={<Page2 />} />
</Routes>
</AnimatePresence>
);
};
function App() {
return (
<BrowserRouter>
<AnimatedRoutes />
</BrowserRouter>
);
}
export default App;

最新更新