javascript - 我想实现反应水平无限滚动。没有得到适当的解决方案。有没有人在 react 或 javasrcipt 中构建过这个
问题描述
我想实现无限水平滚动。但没有找到任何解决方案。我也尝试了一些图书馆,但那些也没有工作。
解决方案
听起来很有趣,给它一个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>
);
}
推荐阅读
- asp.net-core - 在 Azure 中运行应用程序时,Datepicker 日期时间格式不起作用
- database - 如何在低性能 PC 上将大文件插入 Sqlite DB?
- java - 如何让 BluetoothAdapter.startDiscovery() 在我的 Android 10 设备上运行?
- java - 如何释放http连接
- jquery - 模态部分视图验证不起作用
- apache-spark - 从最新的偏移量恢复结构化流
- python-3.x - Python 登录屏幕 Tkinter
- amazon-web-services - 在 Terraform for ECS 中使用 extraHosts 块
- android - 等待调试连接时出错:日志阅读器意外失败 在 iPhone SE(第 2 代)上启动应用程序时出错
- reactjs - React,Redux-Toolkit:无法读取未定义的属性“数据”