我有一个英雄组件,里面有一个背景图像和一个轮播。我想在轮播中滑动上一张和下一张时更改背景图像,具体取决于轮播中当前显示的内容。 CarouselPrev 和 CarouselNext 是从 carousel 组件导出的。它们在那里应用了 onClick 函数,因此我无法将 onClick 函数应用于我的英雄组件中的这些组件,否则它们将相互覆盖。
轮播:
import * as React from "react";
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/Components/ui/Button";
type CarouselApi = UseEmblaCarouselType[1];
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>;
type CarouselOptions = UseCarouselParameters[0];
type CarouselPlugin = UseCarouselParameters[1];
type CarouselProps = {
opts?: CarouselOptions;
plugins?: CarouselPlugin;
orientation?: "horizontal" | "vertical";
setApi?: (api: CarouselApi) => void;
currentIndex: number;
};
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0];
api: ReturnType<typeof useEmblaCarousel>[1];
scrollPrev: () => void;
scrollNext: () => void;
canScrollPrev: boolean;
canScrollNext: boolean;
currentIndex: number;
} & CarouselProps;
const CarouselContext = React.createContext<CarouselContextProps | null>(null);
function useCarousel() {
const context = React.useContext(CarouselContext);
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />");
}
return context;
}
const Carousel = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & CarouselProps
>(
(
{
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
},
ref
) => {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins
);
const [canScrollPrev, setCanScrollPrev] = React.useState(false);
const [canScrollNext, setCanScrollNext] = React.useState(false);
const [currentIndex, setCurrentIndex] = React.useState(0);
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) {
return;
}
setCanScrollPrev(api.canScrollPrev());
setCanScrollNext(api.canScrollNext());
setCurrentIndex(api.selectedScrollSnap());
}, []);
const scrollPrev = React.useCallback(() => {
api?.scrollPrev();
}, [api]);
const scrollNext = React.useCallback(() => {
api?.scrollNext();
}, [api]);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
scrollPrev();
} else if (event.key === "ArrowRight") {
event.preventDefault();
scrollNext();
}
},
[scrollPrev, scrollNext]
);
React.useEffect(() => {
if (!api || !setApi) {
return;
}
setApi(api);
}, [api, setApi]);
React.useEffect(() => {
if (!api) {
return;
}
onSelect(api);
api.on("reInit", onSelect);
api.on("select", onSelect);
return () => {
api?.off("select", onSelect);
};
}, [api, onSelect]);
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
currentIndex
}}
>
<div
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
}
);
Carousel.displayName = "Carousel";
const CarouselContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel();
return (
<div ref={carouselRef} className="overflow-hidden w-1/2 -ml-36">
<div
ref={ref}
className={cn(
"flex flex-row-reverse",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className
)}
{...props}
/>
</div>
);
});
CarouselContent.displayName = "CarouselContent";
const CarouselItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { orientation } = useCarousel();
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-8" : "pt-4",
className
)}
{...props}
/>
);
});
CarouselItem.displayName = "CarouselItem";
const CarouselPrevious = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "bottom-1/4 right-12"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
);
});
CarouselPrevious.displayName = "CarouselPrevious";
const CarouselNext = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "bottom-1/4 right-0"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
);
});
CarouselNext.displayName = "CarouselNext";
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
};
英雄:
import { getTop10 } from "@/lib/utils";
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@/Components/ui/carousel";
import React, { useState, useEffect } from 'react';
import { Card, CardContent } from "@/Components/ui/card";
const Hero = () => {
const [top10, setTop10] = useState<any[]>([]);
useEffect(() => {
const fetchTop10 = async () => {
try {
const movies = await getTop10();
if(Array.isArray(movies?.results)){
setTop10(movies.results.slice(0, 10));
} else {
console.error('Data is not an array:', movies);
}
}
catch(error) {
console.error('Error fetching top10:', error);
}
};
fetchTop10();
}, []);
const [currentMovieIndex, setCurrentMovieIndex] = useState(0);
function handlePreviousClick() {
setCurrentMovieIndex((prevIndex) => (prevIndex === 0 ? top10.length-1 : prevIndex - 1));
}
function handleNextClick() {
setCurrentMovieIndex((prevIndex) => (prevIndex === top10.length-1 ? 0 : prevIndex + 1));
}
return (
<div
style={{ backgroundImage: `url(https://image.tmdb.org/t/p/original/${top10[currentMovieIndex]?.backdrop_path})`, backgroundPosition: "center" }}
className="w-full h-[1000px] bg-cover bg-center"
>
<div className="container mx-auto pt-60 text-6xl text-white font-bold flex flex-col gap-6">
<h1>{top10[currentMovieIndex]?.original_title}</h1>
<div className="flex flex-row gap-4 items-center">
<span className="px-4 py-1 bg-amber-700 text-black text-xl rounded h-fit">
IMDB
</span>
<span className="text-3xl font-medium">{top10[currentMovieIndex]?.vote_average} / 10</span>
</div>
<Carousel
opts={{
align: "end",
direction: "rtl",
loop: true,
duration: 40,
}}
className="w-full mt-20"
currentIndex={0}
>
<CarouselContent>
{top10.map((movie: any, index: number) => (
<CarouselItem key={index} className="basis-1/3">
<div className="p-1">
<Card style={{ backgroundImage: `url(https://image.tmdb.org/t/p/original/${movie?.poster_path})`, backgroundPosition: "center" }} className="bg-cover bg-center w-full">
<CardContent />
</Card>
</div>
</CarouselItem>
))}
</CarouselContent>
<CarouselPrevious />
<CarouselNext />
</Carousel>
</div>
</div>
);
}
export default Hero;
Embla Docs 有一个名为
selectedScrollSnap
的方法,可以跟踪索引,但我不知道如何使用它并将值传递到我的轮播。然后我不确定这是否是尝试实现我正在寻找的功能的正确方法。
不确定我写这篇文章时在做什么。我只是将 Hero 组件内的 CarouselNext 和 CarouselPrevious 组件包装在一个 div 中,并将 onClick 放在这些 div 上。然后摆脱了我在 Carousel 组件中使用 ScrollSnap 所做的所有奇怪的事情。
<div onClick={handlePreviousClick}>
<CarouselPrevious />
</div>
<div onClick={handleNextClick}>
<CarouselNext />
</div>