【问题标题】:Swiper React how to stop and start autoplay on hover with TypescriptSwiper React 如何使用 Typescript 在悬停时停止和开始自动播放
【发布时间】:2021-06-06 09:30:54
【问题描述】:

我将Swiper js 用于我的轮播、React 和 Typescript。

在此post 之后,我尝试在悬停时自动播放stop()start()。我需要这种方法,因为我必须在悬停 Swiper 容器时创建一些状态。

1) 我的ref 组件上的ref 属性出现打字错误:

类型'IntrinsicAttributes & Swiper & 上不存在属性'ref' {孩子?

2) 如何获得对 swiper 的访问权限,以便可以在 handleMouseEnter 函数中使用 swiper.autoplay.stop();?所以我可以像这样使用:

const handleMouseEnter = () => {
  swiper.autoplay.stop();
 };

或喜欢:

const handleMouseEnter = () => {
 swiperRef.current.swiper.autoplay.stop();
};

这是the sandbox 我目前所拥有的。

如何使用 Typescript 让它工作?

【问题讨论】:

    标签: reactjs typescript swiperjs swiper.js


    【解决方案1】:

    您可以在 ref 中初始化 swiper 时存储它,然后像这样使用它的 controllerEvents:

    import React from "react";
    import { Swiper, SwiperSlide } from "swiper/react";
    import SwiperCore, { Autoplay, Pagination } from "swiper";
    
    SwiperCore.use([Pagination, Autoplay]);
    
    export default function SwiperComponent() {
      const swiperRef = React.useRef<SwiperCore>();
      const onInit = (Swiper: SwiperCore): void => {
        swiperRef.current = Swiper;
      };
      const handleMouseEnter = () => {
        if (swiperRef.current) swiperRef.current.autoplay.start();
      };
      const handleMouseLeave = () => {
        if (swiperRef.current) swiperRef.current.autoplay.stop();
      };
    
      return (
        <div onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
          <Swiper onInit={onInit}>
            <SwiperSlide></SwiperSlide>
          </Swiper>
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多