English 中文(简体)
在没有图书馆的情况下,在React Js建立循环车库
原标题:Create a circular carousel in React Js without any library

I am hoping to recreate the carousel present on this site. I want to achieve the same functionality without using any library. I have come across a lot of resources on how to achieve that. Most of them were creating two copies of the carousel track and then switching in between but I do not want to do that. The below code works fine as long as I am sliding within the boundary elements (1st and last slide). How can I switch from the last slide to the first slide and vice versa? I can switch to the first slide from the last slide by adjusting the left offset but that would not make it look like an infinite slider. I want to make it look like the one on the site. Is appending first slide after the last the only way to achieve?

import {useRef, useEffect} from "react";
import {details} from "./constants";

const App = () => {
  const carousel_track = useRef();
  const container = useRef();
  let counter = 0;
  const card = useRef();
  const prevSlide = () => {
    const width = card.current.offsetWidth;
    counter--;
    carousel_track.current.style.left = -width * counter + "px";
  };
  const nextSlide = () => {
    const width = card.current.offsetWidth;
    counter++;
    carousel_track.current.style.left = -width * counter + "px";
  };
  useEffect(() => {
    addEventListener("keydown", (e) => {
      if (e.code === "ArrowRight") nextSlide();
      if (e.code === "ArrowLeft") prevSlide();
    });
  }, []);

  return (
    <div className="w-screen  h-screen flex items-center bg-slate-500">
      <div
        ref={container}
        className="w-screen h-2/3 transition-all  overflow-x-hidden relative border-cyan-800 border-4"
      >
        <div
          onClick={prevSlide}
          className="absolute cursor-pointer  text-2xl text-white z-10 left-0 top-1/2"
        >
          Prev
        </div>
        <div
          onClick={nextSlide}
          className="absolute cursor-pointer text-2xl text-white z-10 right-0 top-1/2"
        >
          Next
        </div>
        <div
          ref={carousel_track}
          className="w-[200%] h-full flex transition-all justify-start items-center absolute bg-red-800"
        >
          {details.map((slide) => (
            <div
              ref={card}
              className="w-screen h-full flex-shrink-0"
              key={slide.title}
            >
              <div className="rounded-lg h-full">
                <img
                  src={slide.image}
                  alt="image"
                  className="rounded-lg w-full h-full object-cover"
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default App;
问题回答

I can provide you with a basic example of a circular carousel in React without using any external libraries.

import React, { useState } from  react ;

const Carousel = ({ images }) => {
  const [currentIndex, setCurrentIndex] = useState(0);

  const nextImage = () => {
    setCurrentIndex((prevIndex) => (prevIndex + 1) % images.length);
  };

  const prevImage = () => {
    setCurrentIndex((prevIndex) => (prevIndex - 1 + images.length) % images.length);
  };

  return (
    <div style={{ position:  relative , width:  300px , margin:  auto  }}>
      <button onClick={prevImage} style={{ position:  absolute , top:  50% , left:  10px  }}>
        { < }
      </button>
      <img
        src={images[currentIndex]}
        alt={`Image ${currentIndex + 1}`}
        style={{ width:  100% , borderRadius:  8px  }}
      />
      <button onClick={nextImage} style={{ position:  absolute , top:  50% , right:  10px  }}>
        { > }
      </button>
    </div>
  );
};

const App = () => {
  const images = [
     https://via.placeholder.com/300 ,
     https://via.placeholder.com/300 ,
     https://via.placeholder.com/300 ,
    // Add more image URLs as needed
  ];

  return (
    <div>
      <h1>React Circular Carousel</h1>
      <Carousel images={images} />
    </div>
  );
};

export default App;




相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签