You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在嵌套组件间传递索引,实现Hero背景随Carousel切换?

解决方案

要实现Hero背景图随Carousel切换同步更新,核心是让Hero组件获取到Carousel内部的当前索引值,具体修改如下:

1. 修改Carousel组件,添加索引变化回调

在Carousel组件中新增回调属性,用于将内部当前索引传递给父组件(Hero):

步骤1:更新CarouselProps类型

在Carousel组件的类型定义中添加onIndexChange回调:

type CarouselProps = {
  opts?: CarouselOptions;
  plugins?: CarouselPlugin;
  orientation?: "horizontal" | "vertical";
  setApi?: (api: CarouselApi) => void;
  onIndexChange?: (index: number) => void; // 新增索引变化回调
};

步骤2:在索引更新时触发回调

修改Carousel组件内部的onSelect函数,当Embla Carousel选中索引变化时,调用父组件传递的回调:

const onSelect = React.useCallback((api: CarouselApi) => {
  if (!api) {
    return;
  }

  setCanScrollPrev(api.canScrollPrev());
  setCanScrollNext(api.canScrollNext());
  const newIndex = api.selectedScrollSnap();
  setCurrentIndex(newIndex);
  // 将最新索引传递给父组件
  props.onIndexChange?.(newIndex);
}, [props.onIndexChange]);

2. 修改Hero组件,同步Carousel索引

在Hero组件中利用Carousel的onIndexChange回调,更新当前电影索引,从而切换背景图:

步骤1:移除无用的点击处理函数

删除Hero中原来的handlePreviousClick和handleNextClick函数,Carousel内部已处理滑动逻辑,无需额外绑定。

步骤2:给Carousel绑定索引变化回调

在Hero的Carousel组件上添加onIndexChange属性,将Carousel的当前索引同步到currentMovieIndex:

<Carousel
  opts={{
    align: "end",
    direction: "rtl",
    loop: true,
    duration: 40,
  }}
  className="w-full mt-20"
  onIndexChange={(index) => setCurrentMovieIndex(index)} // 同步索引
>

原理说明

Embla Carousel的selectedScrollSnap()方法会返回当前选中的滚动快照索引,Carousel组件内部已通过select事件监听索引变化,我们只需将该索引通过回调传递给Hero组件,让Hero根据索引更新背景图和标题等内容即可。这种方式不会覆盖CarouselPrevious和CarouselNext内部的点击事件,而是通过事件监听实现状态同步。

内容的提问来源于stack exchange,提问作者LucasAE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 19:42:04