reactjs - 尝试使用 Framer Motion 制作轮播时出现视觉错误
问题描述
我正在尝试在 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 上的精简版
解决方案
如果您希望一个组件在下一个组件的挂载动画开始之前完成其卸载( exit
) 动画,则必须打开 AnimatePresence 的.exitBeforeEnter
https://www.framer.com/api/motion/animate-presence/#animatepresenceprops.exitbeforeenter
不知道那个视觉错误,因为它在 CodeSandbox 示例中不可见。但这可能是因为该组件(暂时)从 DOM 中删除,这导致事情重新排序。一个解决方案可能是只将motion.div
图像放在里面AnimatePresence
,就像我在这里所做的那样:
推荐阅读
- javascript - 读取数组并显示 html div
- javascript - 通过Angular中的服务单击按钮触发不同组件中的功能?
- sql - sql 从列表中选择 1 项
- sql - 如何从 SQL 查询创建详细报告
- tcp - TCP/IP 数据包数据链路字段
- opencv - 使用openCV计算物质对象
- c# - C# 形式的“必须声明标量变量”错误是什么意思?
- android - Bitrise 无法安装缺少的 android 工具 - Fabric
- google-cloud-platform - 无法使用 PHP Google App Engine 连接 Cloud SQL
- javascript - 自己使用多个 for 循环或将逻辑委托给 Promise 是否更高效?