【问题标题】:i want to implement react horizontal infinite scroll. not getting proper solution . have anyone built this in react or javasrcipt我想实现反应水平无限滚动。没有得到适当的解决方案。有没有人在 react 或 javasrcipt 中构建过这个
【发布时间】:2026-01-28 07:50:01
【问题描述】:

我想实现无限水平滚动。但没有找到任何解决方案。我也尝试了一些图书馆,但那些也没有工作。

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    听起来很有趣,给它一个狂欢

    see here

    供参考

    import React, { useState, useEffect } from "react";
    import "./styles.css";
    
    export default function App() {
      const containerRefDiv = React.useRef();
    
      const [width, setWidth] = useState(0);
      const [currentScrollLeft, setCurrentScrollLeft] = useState(0);
    
      const updateDivWidth = e => {
        const newScrollLeft = containerRefDiv.current.scrollLeft;
        if (currentScrollLeft < newScrollLeft) {
          //only do this if scrolling to the right
          setCurrentScrollLeft(newScrollLeft);
          if (width === 0) {
            //if the width is zero, it has not been initialised yet. Initialise it
            setWidth(containerRefDiv.current.clientWidth + 10);
          } else {
            //add 10, or whatever value you want here
            setWidth(previous => previous + 10);
          }
        }
      };
    
      useEffect(() => {
        console.log("new width set: ", width);
      }, [width]);
    
      const getInnerDivStyle = () => {
        if (containerRefDiv.current && width !== 0) {
          //return the wdith state as the new width if there is a container ref and width is not zero
          return `${width}px`;
        } else {
          //Initialize to a litte more than 100% to enable overflow, if no div ref available
          return "101%";
        }
      };
    
      return (
        <div
          className="App"
          style={{ overflowX: "scroll", width: "100%" }}
          ref={containerRefDiv}
          onScroll={updateDivWidth}
        >
          <div style={{ width: getInnerDivStyle() }}>{width}</div>
        </div>
      );
    }
    

    【讨论】:

      最近更新 更多