滑块无法使用 nextjs 和 tailwinds css 工作

问题描述 投票:0回答:1
"use client";
import React, { useState } from "react";

const textData = [
  {
    id: 1,
    text: "Text 1 Description",
  },
  {
    id: 2,
    text: "Text 2 Description",
  },
  {
    id: 3,
    text: "Text 3 Description",
  },
  {
    id: 4,
    text: "Text 4 Description",
  },
  {
    id: 5,
    text: "Text 5 Description",
  },
];

export default function TextSlider() {
  const [currentIndex, setCurrentIndex] = useState(0);

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

  const handleNext = () => {
    setCurrentIndex((prevIndex) => (prevIndex + 1) % textData.length);
  };

  return (
    <div className="relative w-full h-screen overflow-hidden">
      <button
        className="absolute top-1/2 left-4 text-white text-2xl z-50"
        onClick={handlePrev}
      >
        {"<"}
      </button>
      <div className="w-full h-full flex items-center justify-center overflow-hidden">
        <div
          className="flex transition-transform duration-300 ease-in-out"
          style={{
            transform: `translateX(-${
              (currentIndex * 100) / textData.length - 40
            }%)`,
          }}
        >
          {textData.map((item, index) => (
            <div
              key={item.id}
              className={`w-[100vh] h-full flex items-center justify-center ${
                index === currentIndex ? "transform scale-125" : "opacity-75"
              }`}
            >
              <div className="bg-black bg-opacity-50 text-white p-4">
                <p className="text-lg font-bold text-center">{item.text}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
      <button
        className="absolute top-1/2 right-4 text-white text-2xl"
        onClick={handleNext}
      >
        {">"}
      </button>
    </div>
  );
}
  1. 我尝试创建滑块,但出现错误

    TranslateX 工作得不太好,就像当我有 -{formula} 时我看不到 1 和 2 元素,当我有没有“-”的 {formula} 时我看不到 4 和 5,也是从元素 3 开始中心,所以这是主要问题。如果我下一步滑动,当元素 1 和 2 处于活动状态时,它将保持在 3 上,但当元素 4 处于活动状态时,它将滚动到它。

    所以错误是:

    1. 元素 3 自动位于中心,因为 translatex 为 0%,并且它将自动采用生成元素的 div 中心

    2. 刷卡系统并没有真正工作,因为3位于中心,所以它会在5之后继续刷空,直到到达元素3并且它会去它,所以元素1和2是无法到达的

我尝试通过在 translatex 值中添加 -40 来解决该问题。这有点起作用,因为滑动在 5 处停止并从 3 处重新开始。

reactjs typescript next.js tailwind-css carousel
1个回答
0
投票

解决了问题。有一个 justify-center 使 carousel div 居中,因此为了解决此问题,我刚刚删除了使 div 居中的 justify-center。

© www.soinside.com 2019 - 2024. All rights reserved.