【发布时间】:2021-05-12 15:51:31
【问题描述】:
在我的 React 应用程序中,我需要像在轮播中一样在组件之间切换。我发现此示例仅使用帧运动来构建图像轮播:https://codesandbox.io/s/framer-motion-image-gallery-pqvx3?file=/src/Example.tsx:1715-1725
我想让它适应组件之间的切换。目前我的页面看起来像这样:
const variants = {
enter: (direction: number) => {
return {
x: direction > 0 ? 100 : -100,
opacity: 0,
}
},
center: {
zIndex: 1,
x: 0,
opacity: 1,
},
exit: (direction: number) => {
return {
zIndex: 0,
x: direction < 0 ? 100 : -100,
opacity: 0,
}
},
}
const Page = () => {
const [[page, direction], setPage] = useState([0, 0])
const paginate = (newDirection: number) => {
setPage([page + newDirection, newDirection])
}
return (
<motion.div
key={page}
custom={direction}
variants={variants}
initial="enter"
animate="center"
exit="exit"
>
<!-- my components, between which I want to switch, should appear here -->
</motion.div>
)
}
我将如何构建能够在我的组件(幻灯片)之间动态切换的逻辑?在代码框示例中,图像是通过数组更改的:
const imageIndex = wrap(0, images.length, page);
<motion.img key={page} src={images[imageIndex]} />
如何在 jsx 元素之间切换?
编辑
Joshua Wootonn 的回答是正确的,但您还需要将 custom 属性添加到 TestComp 以使动画与这样的动态变体一起工作:
const TestComp = ({ bg }: { bg: string }) => (
<motion.div
custom={direction}
variants={variants}
initial="enter"
animate="center"
exit="exit"
transition={{
x: { type: "spring", stiffness: 100, damping: 30 },
opacity: { duration: 0.2 },
}}
className="absolute w-full h-full"
style={{
background: bg,
}}
/>
)
【问题讨论】:
标签: reactjs framer-motion