我想实现react水平无限滚动.没有得到正确的解决方案.有人在react或javasrcipt中构建了这个



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

听起来很有趣,给了它一个抨击

参见此处

供参考

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

最新更新