问题描述
我正在编写一个简单的应用程序,我想使用 framer-motion 库添加页面转换。我面临的问题是,我看到的每个教程和文档都在每个组件中使用了
这是我的App.js的回归
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/">
<HomeScreen />
</Route>
<Route exact path="/contact">
<ContactScreen />
</Route>
<Route exact path="/aboutus">
<AboutUsScreen />
</Route>
</Switch>
</div>
</Router >
);
如果我想添加动画,我必须在每个组件中添加
<Route exact path="/">
<motion.div initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
<HomeScreen />
</motion.div>
</Route>
从上周开始我就一直坚持这个。如果有人能帮我解决这个问题,我将不胜感激!
解决方法
所以,如果我理解正确,那么你可以这样做:
第一个:创建一个如下所示的自定义组件
import React from "react";
import { motion } from "framer-motion";
interface IProps {
initial: {};
animate: {};
children: any;
transition: {};
component: string;
className: string;
exit?: {}; // can be undefined
}
const AnimatedFramerMotionComponent = ({
exit,initial,animate,children,component,className,transition,}: IProps) => {
const CustomComponent: any = motion(component);
return (
<CustomComponent
initial={initial}
animate={animate}
exit={exit}
transition={transition}
className={className}
>
{children}
</CustomComponent>
);
};
export default AnimatedFramerMotionComponent;
第二:像这样使用
<AnimatedFramerMotionComponent
component="h1"
initial={{ y: "-100%",opacity: 0 }}
animate={{ y: 0,opacity: 1 }}
transition={{ delay: 1 }}
className="text-white text-8xl"
>
Regenci
</AnimatedFramerMotionComponent>