我正在尝试在 React 中使用 Framer Motion 制作轮播,但我遇到了一个视觉错误。以前的组件在新组件之前没有被卸载,我得到了一个奇怪的效果。这个Gyazo
这是处理一切的组件:
const ProjectList = props => {
const [page, setPage] = useState(0);
const projects = [
<Project
name="Example"
desc="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Libero nunc consequat interdum varius sit amet."
image={require("../img/office.jpg")}
/>,
<Project
name="Example2"
desc="Another example. This one does nothing too. What a suprise!"
image={require("../img/office.jpg")}
/>
]
const paginate = (newPage) => {
if(newPage < 0) {
setPage(projects.length - 1)
} else if (newPage > projects.length - 1) {
setPage(0);
} else {
setPage(newPage);
}
}
return (
<div className="project-list">
<AnimatePresence>
<motion.button
key="previous"
onClick={() => paginate(page-1)}
className="carousel-btn"
whileHover={{scale: 1.5, transition: {duration: 0.5}}}
>
<ArrowBackIosIcon/>
</motion.button>
<motion.div
key={page}
initial={{opacity: 0}}
animate={{opacity: 1}}
exit={{opacity: 0}}
>
{projects[page]}
</motion.div>
<motion.button
key="next"
onClick={() => paginate(page+1)}
className="carousel-btn"
whileHover={{scale: 1.5, transition: {duration: 0.5}}}>
<ArrowForwardIosIcon/>
</motion.button>
</AnimatePresence>
</div>
);
};
我不知道如何在片段工具中使用像 framer-motion 这样的库,所以这是 CodeSandbox 上的精简版