在Framer Motion中,可以通过使用AnimateSharedLayout和AnimatePresence组件来实现这一效果。首先,为每张图片设置相同的布局,并在图片之间使用motion.div。然后,在onClick事件中切换图片的可见性,可使用motion.div的initial和animate属性来控制图片的淡入淡出效果。以下是示例代码:
import { useState } from "react";
import { motion, AnimateSharedLayout, AnimatePresence } from "framer-motion";
const images = [
{ id: 1, src: "image1.jpg" },
{ id: 2, src: "image2.jpg" },
{ id: 3, src: "image3.jpg" },
export default function ImageCarousel() {
const [selectedId, setSelectedId] = useState(1);
return (
<AnimateSharedLayout>
<div className="image-list">
{images.map((image) => (
<motion.div
key={image.id}
className="image-container"
layoutId={image.id.toString()}
onClick={() => setSelectedId(image.id)}
{selectedId === image.id && (
<motion.img
src={image.src}
layoutId={`image-${image.id.toString()}`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
</motion.div>
</AnimateSharedLayout>