React实现一个简易版Swiper( 三 )

))} );}export default Swiper;至此为止,我们整体的dom结构与样式就编写完成了,后面要做的就是如何让他们按照我们想要的那样,动起来 。
4、动画实现既然说到了轮播动画的实现,那么我们最先想到的也是最方便的方式,肯定是我们最熟悉的setInterval,那么整体的实现思路是什么样的呢?
先思考一下我们想要实现的功能:1、按照预设的参数实现定时的图片切换功能;2、如果没有预设delay的话,则不自动轮播;3、每次轮播的距离,是由用户配置的图片宽高决定;4、轮播至最后一张后,停止轮播 。
首先,为了保证元素可以正常的移动,我们在元素身上添加ref和id便于获取正确的dom元素 。
import React, { FC, useRef } from "react";const swiperContainerRef = useRef<HTMLDivElement>(null);...<SwiperContainer  id="swiper-container"  ref={swiperContainerRef}  style={{    height,    // 根据轮播方向参数,调整flex布局方向    flexDirection: direction === "horizontal" ? "row" : "column",  }}>...</SwiperContainer>...其次,我们需要定义activeIndex这个state,用来标记当前展示的节点;以及用isDone标记是否所有图片都已轮播完成(所以反馈参数) 。
import React, { FC, useState } from "react";const [activeIndex, setActiveIndex] = useState<number>(0);const [isDone, setDone] = useState<boolean>(false);然后,我们还需要进行timer接收参数的定义,这里我们可以选择使用useRef来进行定义 。
import React, { FC, useRef } from "react";const timer = useRef<any>(null);在上面的一切都准备就绪后,我们可以进行封装启动方法的封装
  // 使用定时器,定时进行activeIndex的替换  const startPlaySwiper = () => {    if (speed <= 0) return;    timer.current = setInterval(() => {      setActiveIndex((preValue) => preValue + 1);    }, speed * 1000);  };但是到此为止,我们只是进行了activeIndex的自增,并没有真正的让页面上的元素动起来,为了实现真正的动画效果,我们使用useEffect对于activeIndex进行监听 。
import React, { FC, useEffect, useRef, useState } from "react";useEffect(() => {  const swiper = document.querySelector("#swiper-container") as any;  // 根据用户传入的轮播方向,决定是在bottom上变化还是right变化  if (direction === "vertical") {    // 兼容用户输入百分比的模式    swiper.style.bottom = (height as string)?.includes("%")      ? `${activeIndex * +(height as string)?.replace("%", "")}vh`      : `${activeIndex * +height}px`;  } else {    swiper.style.right = (width as string)?.includes("%")      ? `${activeIndex * +(width as string)?.replace("%", "")}vw`      : `${activeIndex * +width}px`;  // 判断如果到达最后一张,停止自动轮播  if (activeIndex >= urls.length - 1) {    clearInterval(timer?.current);    timer.current = null;    setDone(true);  }}, [activeIndex, urls]);

经验总结扩展阅读