如何在 React 中创建一个简单的 Carousel/Slider

发布: (2026年1月8日 GMT+8 23:09)
3 min read
原文: Dev.to

Source: Dev.to

轮播组件

轮播(或滑块)是一次显示一张图片或内容的绝佳方式。你可以使用按钮在它们之间导航。下面是使用 React 实现的一个简单示例。

import { useEffect, useState } from 'react';
import { shortList, list, longList } from '../data';
import { FaQuoteRight } from 'react-icons/fa';
import { FiChevronLeft, FiChevronRight } from 'react-icons/fi';

const Carousel = () => {
  const [people, setPeople] = useState(longList);
  const [currentPersonIndex, setCurrentPersonIndex] = useState(0);

  const prevSlide = () => {
    setCurrentPersonIndex((oldIndex) => {
      const newIndex = (oldIndex - 1 + people.length) % people.length;
      return newIndex;
    });
  };

  const nextSlide = () => {
    setCurrentPersonIndex((oldIndex) => {
      const newIndex = (oldIndex + 1) % people.length;
      return newIndex;
    });
  };

  useEffect(() => {
    const sliderId = setInterval(() => {
      nextSlide();
    }, 2000);

    return () => {
      clearInterval(sliderId);
    };
  }, [currentPersonIndex]);

  return (
    {people.map((person, personIndex) => {
      const { id, name, image, title, quote } = person;
      return (
        <div key={id}>
          <h3>{name}</h3>
          <p>{title}</p>
          <p>{quote}</p>
        </div>
      );
    })}
  );
};

export default Carousel;

函数说明:nextSlideprevSlide

nextSlide 函数

const nextSlide = () => {
  setCurrentPersonIndex((oldIndex) => {
    const newIndex = (oldIndex + 1) % people.length;
    return newIndex;
  });
};

工作原理

  • 读取当前索引(currentPersonIndex)。
  • 加 1 以移动到下一个项目。
  • 取模运算符(% people.length)在到达列表末尾时将索引重新包装回 0,从而形成连续循环。

示例

如果 currentPersonIndex 为 4(最后一个人),且列表有 5 项,(4 + 1) % 5 的结果是 0,因此轮播返回到第一个人。

prevSlide 函数

const prevSlide = () => {
  setCurrentPersonIndex((oldIndex) => {
    const newIndex = (oldIndex - 1 + people.length) % people.length;
    return newIndex;
  });
};

工作原理

  • 读取当前索引。
  • 减 1 以移动到上一个项目。
  • 在取模之前先加上 people.length,确保结果为正数,从而实现从第一个项目回到最后一个项目的包装。

示例

如果 currentPersonIndex 为 0(第一个人),且列表有 5 项,(-1 + 5) % 5 的结果是 4,轮播移动到最后一个人。

关键要点

  • 表达式 % people.length 使轮播能够在前进和后退时都实现环绕。
  • nextSlide 增加索引;prevSlide 减少索引。
  • 更新 currentPersonIndex 会触发重新渲染,显示相应的幻灯片。
Back to Blog

相关文章

阅读更多 »

React 峰会 2026

React Summit 2026 的封面图片 https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.a...