问题描述
浏览器控制台错误
You're attempting to animate multiple children within AnimatePresence,but its exitBeforeEnter prop is set to true. This will lead to odd visual behavIoUr.
App.js(包含在browserRouter中)
<Switch>
<AnimatePresence exitBeforeEnter>
<Route key="1" exact path="/" component={Home}/>
<Route key="2" exact path="/home" component={Home}/>
<Route key="3" exact path="/articles" component={Articles}/>
</AnimatePresence>
</Switch>
Home.js / Articles.js
const Home = props =>{
return(
<motion.h1 initial={{x:-100}} animate={{x:0}} exit={{x:-100}}>Home/Articles</motion.h1>
)
}
export default Articles
任何人都可以解释导致错误的原因吗?
解决方法
如文档所述,关于exitBeforeEnter
:
如果设置为true,则AnimatePresence一次仅渲染一个组件。退出组件将在渲染进入组件之前完成退出动画。
因此启用此道具后,您会希望以另一种方式将Switch
换成AnimatePresence
<AnimatePresence exitBeforeEnter>
<Switch location={location} key={location.pathname}>
<Route exact path="/" component={Home}/>
<Route exact path="/home" component={Home}/>
<Route exact path="/articles" component={Articles}/>
</Switch>
</AnimatePresence>
请注意,您还需要为key
传递Switch