首页 > 解决方案 > 我想实现反应水平无限滚动。没有得到适当的解决方案。有没有人在 react 或 javasrcipt 中构建过这个

问题描述

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

标签: javascripthtmlreactjs

解决方案


听起来很有趣,给它一个bash

看这里

以供参考

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>
  );
}

推荐阅读