如何使用鼠标滚轮进行反应水平滚动

How to do React-horizontal scroll using mouse wheel

我在 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>

您可以使用自定义滚动功能作为 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作为示例。