【问题标题】:React Router and framer motion Animate Presence反应路由器和成帧器运动动画存在
【发布时间】:2020-08-27 11:15:35
【问题描述】:
当我将“exitBeforeEnter”道具添加到具有嵌套路由的 Animate Presence 组件时,这些路由根本没有呈现,但是当我刷新它们呈现的页面时,删除此道具或直接转到组件将修复它,但是我需要使用 react-router 中的 prop 和重定向组件
这是我的代码:
<AnimatePresence exitBeforeEnter>
<Switch location={this.props.location} key={this.props.location.pathname} >
<Route exact path='/home' component={() => <.../>
<Route path='/home/:alpha3Code' component={({match}) =>
.... />
<Redirect to='/home' />
</Switch>
</AnimatePresence>
【问题讨论】:
标签:
javascript
reactjs
framer-motion
【解决方案1】:
来自exitBeforeEnter docs
如果设置为true,AnimatePresence 一次只会渲染一个组件。退出组件会在进入组件渲染之前完成退出动画。
您必须为您在AnimatePresence 中使用的所有组件指定exit 动画。在路由更改时,AnimatePresence 将首先执行 exit 动画,然后才渲染下一个组件。如果一个组件没有exit动画并且它是AnimatePresence的子组件,那么路由改变只会改变url而不是视图。
【解决方案2】:
如果您不为每条路线添加exit 动画,这很正常。
AnimatePresense 的主要路线
<AnimatePresence exitBeforeEnter>
<Switch location={window.location} key={window.location.pathname}>
<Route exact path='/' component={Home} />
<Route exact path='/about' component={About} />
<Route path="*">Page not found</Route>
</Switch>
</AnimatePresence
关于.jsx
const exit = {
exit: {
opacity: 0,
},
}
export default function About() {
return <motion.h1 {...exit}>Hello</h1>
}
Home.jsx
const exit = {
exit: {
opacity: 0,
},
}
export default function Home() {
return <motion.h1 {...exit}>Hello</h1>
}
【解决方案3】:
对于那些仍然迷路的人,您需要将 标记包装在 标记周围,并使用其他答案中提到的“退出”参数。下面提供了示例代码。
return (
<motion.div exit='exit' variants={PageTransition} initial='hidden' animate='show' className='login-container'>
<Redirect to='/Dashboard' />
</motion.div>
);
【解决方案4】:
有人有 react-router-dom v6 的更新吗?
我正在重写几个月前制作的一个小应用程序,它之前运行良好,带有AnimatePresence 和Switch 路由器组件。页面更改之间的退出转换已成功运行。
现在由于某种原因,退出转换不会在页面更改时触发,我怀疑这可能是因为对 react-router-dom API 和组件使用所做的更改。
在 react-router-dom v6 中,它看起来更像这样:
const App = function () {
return (
<AnimatePresence exitBeforeEnter>
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route
path="characters"
element={<Characters />}
/>
</Route>
<Route path="login" element={<Login />} />
</Routes>
</BrowserRouter>
</AnimatePresence>
);
};
还有Layout 组件:
<motion.div
key="layout"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.7 }}
>
<Menu />
<div>
<Outlet />
</div>
</motion.div>
很遗憾,没有触发退出转换。
【讨论】:
-
查看answer。它有一个使用 React Router v6 的工作示例。