Недоделаная практика, надо обязательно доделать
This commit is contained in:
+47
-3
@@ -1,10 +1,54 @@
|
||||
// удаляем все, оставляя лишь пустую функцию App ниже
|
||||
import { useState, useRef } from 'react'
|
||||
import './App.scss'
|
||||
|
||||
function VirtualList({ items, itemHeight=50, containerHeight=400 }) {
|
||||
const containerRef = useRef(null)
|
||||
const [scrollTop,setScrollTop] = useState(0);
|
||||
const visibleCount = Math.ceil(containerHeight / itemHeight);
|
||||
const totalHeight = items.length * itemHeight;
|
||||
const startIndex = Math.floor(scrollTop / itemHeight);
|
||||
const endIndex = Math.min(startIndex + visibleCount + 1, items.length);
|
||||
|
||||
const visibleItems = items.slice(startIndex,endIndex);
|
||||
|
||||
const handleScroll = e => {
|
||||
setScrollTop(e.target.scrollTop);
|
||||
console.log(e.target.scrollTop)
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="container" style={{
|
||||
height: containerHeight
|
||||
}} onScroll={handleScroll}>
|
||||
<div style={{ height:totalHeight, position: 'relative' }}>
|
||||
<div style={{position:'absolute', top: 0, left:0, right: 0}}>
|
||||
{visibleItems.map(item => (
|
||||
<div className="item" key={item.id} style={{ height: itemHeight }}>
|
||||
{item.name}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function App() {
|
||||
const generatedBigDataSet = () => {
|
||||
return Array.from({ length: 100 }, (_, index) => ({
|
||||
id: index,
|
||||
name: `Элемент № ${index}`,
|
||||
value: Math.floor(Math.random() * 1000)
|
||||
}))
|
||||
}
|
||||
const [data] = useState(generatedBigDataSet);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Добавьте тестовый контент для проверки */}
|
||||
<h1>Hello, React!</h1>
|
||||
<div>
|
||||
<h2>Визуализация большого списка</h2>
|
||||
<VirtualList items={data} itemHeight={60} containerHeight={500} />
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user