[英]How to use Framer Motion <AnimatePresence> and React Portals?
[英]Framer Motion AnimatePresence doesn't execute when changing routes
我在使用 Framer Motion 库时遇到问题,尤其是 AnimatePresence 过渡。 我可以让它在正常情况下工作,但是当我将路由包装在自定义实现中时,我无法让出口 animation 工作。
当我导航到不同的路线时,我确认使用组件上的 useEffect 挂钩正在卸载,但退出 animation 不是由父级 AnimatePresence 触发的。
任何帮助将不胜感激。
这是我的代码:
应用程序.ts
const App = () => {
const auth: AuthContextState = useContext(AuthContext);
const db: FirestoreContextProps = useContext(FirestoreContext);
const components = {
home: HomeScreen,
classes: ClassScreen,
users: UserScreen,
login: LoginScreen
}
return (
<Background>
<Navbar/>
<Dashboard isLoggedIn={auth.data.authenticated}>
<AnimatedRoutes>
<RouteTransition path={`/home`} key={0}>
<HomeScreen key={0} />
</RouteTransition>
<RouteTransition path={`/classes`} key={1}>
<ClassScreen key={1} />
</RouteTransition>
<RouteTransition path={`/users`} key={2}>
<UserScreen key={2} />
</RouteTransition>
<RouteTransition path={'/login'} key={3}>
<LoginScreen key={3} />
</RouteTransition>
<RouteTransition exact path={'/'} key={4}>
<Redirect to={'/home'}/>
</RouteTransition>
</AnimatedRoutes>
</Dashboard>
</Background>
);
}
动画路线:
type Props = {
exitBeforeEnter?: boolean
initial?: boolean
}
export const AnimatedRoutes: FC<Props> = ({
children,
exitBeforeEnter = true,
initial = false,
}) => {
return (
<AnimatePresence exitBeforeEnter={exitBeforeEnter} initial={initial}>
<Switch>
{children}
</Switch>
</AnimatePresence>
)
}
type RouteProps = {
key: number
exact?: boolean
path: string
slide?: number
slideUp?: number
}
export const RouteTransition: FC<RouteProps> = ({
children,
key,
exact = false,
path,
slide= 0,
slideUp = 0,
...rest
}) => {
return (
<Route path={path} exact={exact} {...rest}>
<MountTransition key={key} >
{children}
</MountTransition>
</Route>
)
}
安装过渡:
type Props = {
key: number
slide?: number
slideUp?: number
}
const Container = styled(motion.div)`
display: flex;
height: 100%;
width: 100%;
`
export const MountTransition: FC<Props> = ({
children,
key,
slide = 0,
slideUp = 0,
}) => {
return (
<Container
key={key}
initial={{opacity: 0, x: slide, y: slideUp}}
animate={{opacity: 1, x: 0, y: 0}}
exit={{opacity: 0, x: slide, y: slideUp}}
transition={{type: 'tween', duration: 2, ease: 'easeInOut'}}
>
{children}
</Container>
)
}
尝试这样的事情:
<Route
render={({location}) => {
return (
<AnimatePresence exitBeforeEnter>
<Switch location={location} key={location.key}>
<Route .../>
<Route .../>
<Route .../>
</Switch>
</AnimatePresence>
)
}}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.