以下是一个使用React框架和TypeScript实现的无缝滚动组件的示例代码:
import React, { useRef, useEffect } from "react";
interface SeamlessScrollProps {
children: React.ReactNode;
}
const SeamlessScroll: React.FC<SeamlessScrollProps> = ({ children }) => {
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!containerRef.current) return;
const container = containerRef.current;
// 计算容器高度
const computeContainerHeight = () => {
const firstChild = container.firstChild as HTMLElement;
const childHeight = firstChild.offsetHeight;
const childCount = container.children.length;
return `${childHeight * childCount}px`;
};
// 复制一份完全相同的列表
const duplicateList = () => {
const listClone = container.cloneNode(true);
container.appendChild(listClone);
};
// 动画循环
let animationId: number;
const startAnimationLoop = () => {
let scrollDistance = 0;
const stepSize = 1; // 滚动速率
function scroll() {
if (!container) return;
scrollDistance += stepSize;
container.style.transform = `translateY(-${scrollDistance}px)`;
// 当滚动距离超过容器高度时,重置滚动位置
if (scrollDistance >= parseInt(computeContainerHeight())) {
scrollDistance = 0;
}
animationId = requestAnimationFrame(scroll);
}
scroll();
};
duplicateList();
startAnimationLoop();
return () => cancelAnimationFrame(animationId);
}, []);
return <div ref={containerRef}>{children}</div>;
};
export default SeamlessScroll;
你可以将该组件嵌入到你的React应用中,并传入需要滚动的内容作为子节点。例如:
import React from "react";
import SeamlessScroll from "./SeamlessScroll";
const App: React.FC = () => {
return (
<div>
<h1>无缝滚动示例</h1>
<SeamlessScroll>
<ul>
<li>列表项1</li>
<li>列表项2</li>
<li>列表项3</li>
{/* 更多列表项... */}
</ul>
</SeamlessScroll>
</div>
);
};
export default App;
请注意,上述代码仅提供了基本的实现思路,如果需要进一步定制样式和功能,请根据自己的需求进行调整和扩展。
内容由零声教学AI助手提供,问题来源于学员提问




