reactjs 如何使用鼠标滚轮进行React水平滚动

z0qdvdin  于 2023-10-17  发布在  React
关注(0)|答案(4)|浏览(189)

我在react js上使用了tailwind-CSS,我想当用户悬停在卡片部分时使用鼠标滚轮水平滚动,这样对于pc用户来说就可以使用鼠标滚轮水平滚动,而不是同时使用shift和鼠标滚轮。任何地方生活

<div className="flex space-x-3 overflow-y-scroll scrollbar-hide p-3 -ml-3">
          {cardsDate?.map(({ img, title }) => (
            <MediumCard key={img} img={img} title={title} /> 
          ))}
        </div>
    </section>

xqkwcwgp

xqkwcwgp1#

您可以使用自定义滚动函数作为div的引用。

export function useHorizontalScroll() {
  const elRef = useRef();
  useEffect(() => {
    const el = elRef.current;
    if (el) {
      const onWheel = e => {
        if (e.deltaY == 0) return;
        e.preventDefault();
        el.scrollTo({
          left: el.scrollLeft + e.deltaY,
          behavior: "smooth"
        });
      };
      el.addEventListener("wheel", onWheel);
      return () => el.removeEventListener("wheel", onWheel);
    }
  }, []);
  return elRef;
}

上述函数可以导入并使用如下:

<div className="App" ref={scrollRef} style={{ overflow: "auto" }}>
      <div style={{ whiteSpace: "nowrap" }}>
        <Picture />
      </div>
    </div>

我创建了一个codesandbox作为示例。

b91juud3

b91juud32#

尝试使用scroll通过运行良好

const element = document.querySelector("#container");

element.addEventListener('wheel', (event) => {
  event.preventDefault();

  element.scrollBy({
    left: event.deltaY < 0 ? -30 : 30,
    
  });
});

容器及其子元素

v9tzhpje

v9tzhpje3#

你可以在不使用refs或hook的情况下通过以下代码内联地实现这一点:

<div
  style={{ scrollbarColor="transparent", overflowX="auto" }}
  onWheel={(e) => {
    // here im handling the horizontal scroll inline, without the use of hooks
    const strength = Math.abs(e.deltaY);
    if (e.deltaY === 0) return;

    const el = e.currentTarget;
    if (
      !(el.scrollLeft === 0 && e.deltaY < 0) &&
      !(
        el.scrollWidth -
          el.clientWidth -
          Math.round(el.scrollLeft) ===
          0 && e.deltaY > 0
      )
    ) {
      e.preventDefault();
    }
    el.scrollTo({
      left: el.scrollLeft + e.deltaY,
      // large scrolls with smooth animation behavior will lag, so switch to auto
      behavior: strength > 70 ? "auto" : "smooth",
    });
  }}
>
// ...
</div>
vdgimpew

vdgimpew4#

hd3adcode的版本是完美的。下面是typescript版本:

export function useHorizontalScroll<T extends HTMLElement>() {
  const elRef = useRef<T>(null);
  useEffect(() => {
    const el = elRef.current;
    if (el) {
      const onWheel = (e: WheelEvent) => {
        if (e.deltaY == 0) return;
        e.preventDefault();
        el.scrollTo({
          left: el.scrollLeft + e.deltaY,
          behavior: 'smooth',
        });
      };
      el.addEventListener('wheel', onWheel);
      return () => el.removeEventListener('wheel', onWheel);
    }
  }, []);
  return elRef;
}

相关问题