英文:
Using scrollTo in React
问题
以下是您提供的代码的翻译部分:
我正在构建一个轮播组件,我需要在用户按下导航按钮时使其滚动,到目前为止,我的代码如下,但滚动功能不起作用:
import React, { FC, useRef, useEffect, useState } from "react";
const Carousel: FC = () => {
  const [activeSlide, setActiveSlide] = useState(0);
  const slides = Array.from({ length: 6 }, (_, index) => ({
    data: `Slide ${index + 1}`
  }));
  const containerRef = useRef<HTMLDivElement>(null);
  const slideRefs = useRef<HTMLDivElement[]>([]);
  const isLeftEnabled = activeSlide !== 0;
  const isRightEnabled = activeSlide !== slides.length - 1;
  useEffect(() => {
    if (containerRef.current) {
      containerRef.current.scrollTo(500, 0);
      console.log("scroll");
      console.log("containerRef.current", containerRef.current);
      //逐个打印所有变量
    }
  }, [activeSlide, slides]);
  return (
    <div className="flex flex-col items-center w-3/5">
      <div className="w-full overflow-x-scroll overflow-y-hidden carousel-container">
        <div className="flex gap-10 w-screen mb-8" ref={containerRef}>
          {slides.map((slide, index) => (
            <div
              className={`slide ${
                activeSlide === index ? "bg-purple-500" : "bg-green-400"
              } rounded-2xl h-52 w-40 flex place-items-center
    select-none`}
              key={`slide-${index}`}
            >
              <p className="m-auto">{slide.data}</p>
            </div>
          ))}
        </div>
      </div>
      <div className="flex gap-6">
        <button
          onClick={() => {
            isLeftEnabled && setActiveSlide(activeSlide - 1);
          }}
          className={`rounded-full w-20 h-20 ${
            isLeftEnabled ? "bg-green-600" : "bg-gray-300"
          }`}
        >
          ◀
        </button>
        <button
          onClick={() => {
            isRightEnabled && setActiveSlide(activeSlide + 1);
          }}
          className={`rounded-full w-20 h-20 ${
            isRightEnabled ? "bg-green-600" : "bg-gray-300"
          }`}
        >
          ▶
        </button>
      </div>
    </div>
  );
};
export default Carousel;
您还提供了一个包含问题的CodeSandbox链接。如果您需要更多帮助,可以提供更多详细信息,我将尽力为您提供支持。
英文:
I'm building a carousel component and I need it to scroll when the user presses the navigation buttons, so far my code is like this but the scroll is not working :
import React, { FC, useRef, useEffect, useState } from "react";
const Carousel: FC = () => {
  const [activeSlide, setActiveSlide] = useState(0);
  const slides = Array.from({ length: 6 }, (_, index) => ({
    data: `Slide ${index + 1}`
  }));
  const containerRef = useRef<HTMLDivElement>(null);
  const slideRefs = useRef<HTMLDivElement[]>([]);
  const isLeftEnabled = activeSlide !== 0;
  const isRightEnabled = activeSlide !== slides.length - 1;
  useEffect(() => {
    if (containerRef.current) {
      containerRef.current.scrollTo(500, 0);
      console.log("scroll");
      console.log("containerRef.current", containerRef.current);
      //console all variables one by one
    }
  }, [activeSlide, slides]);
  return (
    <div className="flex flex-col items-center w-3/5">
      <div className="w-full overflow-x-scroll overflow-y-hidden carousel-container">
        <div className="flex gap-10 w-screen mb-8" ref={containerRef}>
          {slides.map((slide, index) => (
            <div
              className={`slide ${
                activeSlide === index ? "bg-purple-500" : "bg-green-400"
              } rounded-2xl h-52 w-40 flex place-items-center
    select-none`}
              key={`slide-${index}`}
            >
              <p className="m-auto">{slide.data}</p>
            </div>
          ))}
        </div>
      </div>
      <div className="flex gap-6">
        <button
          onClick={() => {
            isLeftEnabled && setActiveSlide(activeSlide - 1);
          }}
          className={`rounded-full w-20 h-20 ${
            isLeftEnabled ? "bg-green-600" : "bg-gray-300"
          }`}
        >
          &#9664;
        </button>
        <button
          onClick={() => {
            isRightEnabled && setActiveSlide(activeSlide + 1);
          }}
          className={`rounded-full w-20 h-20 ${
            isRightEnabled ? "bg-green-600" : "bg-gray-300"
          }`}
        >
          &#9654;
        </button>
      </div>
    </div>
  );
};
export default Carousel;
I have created a codesandbox with the problem :
https://codesandbox.io/s/carousel-scroll-problem-9solvt?file=/src/Carousel.tsx:0-2022
答案1
得分: 1
由于您指定的元素 containerRef 不可滚动,请将具有类 overflow-x-scroll(当前 containerRef 的父元素)的元素指定为 ref={containerRef},它将起作用。
英文:
Since the element you specify containerRef is not scrollable specify the element with class overflow-x-scroll (parent of current containerRef) as ref={containerRef} it will work
答案2
得分: 1
你已经在错误的容器上设置了ref。应该设置在父容器上,因为它具有overflow-x-scroll类。
<div className="w-full overflow-x-scroll overflow-y-hidden carousel-container" 
     ref={containerRef}>
英文:
You have the ref set on the wrong container. It should be the parent, as it has the overflow-x-scroll class.
<div className="w-full overflow-x-scroll overflow-y-hidden carousel-container" 
     ref={containerRef}>
答案3
得分: 1
以下是已翻译好的内容:
some modifications that you'll have to do:
        useEffect(() => {
        if (containerRef.current) {
    // modify below logic by calculating the width and scroll position of container
          if (activeSlide === 2) containerRef.current.scrollTo(0, 0);
          if (activeSlide === 3) containerRef.current.scrollTo(500, 0);
    
          console.log("scroll");
          console.log("containerRef.current", containerRef.current);
          //console all variables one by one
        }
      }, [activeSlide, slides]);
the template:
        ...<div className="w-full overflow-x-scroll overflow-y-hidden carousel-container" ref={containerRef}>
        <div className="flex gap-10 w-screen mb-8">...
英文:
some modifications that you'll have to do:
    useEffect(() => {
if (containerRef.current) {
// modify below logic by calculating the width and scroll position of container
if (activeSlide === 2) containerRef.current.scrollTo(0, 0);
if (activeSlide === 3) containerRef.current.scrollTo(500, 0);
console.log("scroll");
console.log("containerRef.current", containerRef.current);
//console all variables one by one
}
}, [activeSlide, slides]);
the template:
    ...<div className="w-full overflow-x-scroll overflow-y-hidden carousel-container" ref={containerRef}>
<div className="flex gap-10 w-screen mb-8">...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论