【问题标题】:How to do React-horizontal scroll using mouse wheel如何使用鼠标滚轮进行 React 水平滚动
【发布时间】:2021-10-09 23:17:58
【问题描述】:

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

【问题讨论】:

    标签: reactjs tailwind-css


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 2014-07-20
      相关资源
      最近更新 更多