使用 scrollTo 在 React 中

huangapple go评论72阅读模式
英文:

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"
          }`}
        >
          &#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;

您还提供了一个包含问题的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 &quot;react&quot;;

const Carousel: FC = () =&gt; {
  const [activeSlide, setActiveSlide] = useState(0);
  const slides = Array.from({ length: 6 }, (_, index) =&gt; ({
    data: `Slide ${index + 1}`
  }));

  const containerRef = useRef&lt;HTMLDivElement&gt;(null);
  const slideRefs = useRef&lt;HTMLDivElement[]&gt;([]);

  const isLeftEnabled = activeSlide !== 0;
  const isRightEnabled = activeSlide !== slides.length - 1;

  useEffect(() =&gt; {
    if (containerRef.current) {
      containerRef.current.scrollTo(500, 0);
      console.log(&quot;scroll&quot;);
      console.log(&quot;containerRef.current&quot;, containerRef.current);
      //console all variables one by one
    }
  }, [activeSlide, slides]);

  return (
    &lt;div className=&quot;flex flex-col items-center w-3/5&quot;&gt;
      &lt;div className=&quot;w-full overflow-x-scroll overflow-y-hidden carousel-container&quot;&gt;
        &lt;div className=&quot;flex gap-10 w-screen mb-8&quot; ref={containerRef}&gt;
          {slides.map((slide, index) =&gt; (
            &lt;div
              className={`slide ${
                activeSlide === index ? &quot;bg-purple-500&quot; : &quot;bg-green-400&quot;
              } rounded-2xl h-52 w-40 flex place-items-center
    select-none`}
              key={`slide-${index}`}
            &gt;
              &lt;p className=&quot;m-auto&quot;&gt;{slide.data}&lt;/p&gt;
            &lt;/div&gt;
          ))}
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div className=&quot;flex gap-6&quot;&gt;
        &lt;button
          onClick={() =&gt; {
            isLeftEnabled &amp;&amp; setActiveSlide(activeSlide - 1);
          }}
          className={`rounded-full w-20 h-20 ${
            isLeftEnabled ? &quot;bg-green-600&quot; : &quot;bg-gray-300&quot;
          }`}
        &gt;
          &amp;#9664;
        &lt;/button&gt;
        &lt;button
          onClick={() =&gt; {
            isRightEnabled &amp;&amp; setActiveSlide(activeSlide + 1);
          }}
          className={`rounded-full w-20 h-20 ${
            isRightEnabled ? &quot;bg-green-600&quot; : &quot;bg-gray-300&quot;
          }`}
        &gt;
          &amp;#9654;
        &lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

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类。

&lt;div className=&quot;w-full overflow-x-scroll overflow-y-hidden carousel-container&quot; 
     ref={containerRef}&gt;
英文:

You have the ref set on the wrong container. It should be the parent, as it has the overflow-x-scroll class.

&lt;div className=&quot;w-full overflow-x-scroll overflow-y-hidden carousel-container&quot; 
     ref={containerRef}&gt;

答案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(() =&gt; {
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(&quot;scroll&quot;);
console.log(&quot;containerRef.current&quot;, containerRef.current);
//console all variables one by one
}
}, [activeSlide, slides]);

the template:

    ...&lt;div className=&quot;w-full overflow-x-scroll overflow-y-hidden carousel-container&quot; ref={containerRef}&gt;
&lt;div className=&quot;flex gap-10 w-screen mb-8&quot;&gt;...

huangapple
  • 本文由 发表于 2023年2月24日 13:23:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定