Skip to content

Commit

Permalink
test: 编写虚拟列表
Browse files Browse the repository at this point in the history
  • Loading branch information
xie392 committed Jun 2, 2024
1 parent 9d7ac7d commit eb9099d
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 307 deletions.
2 changes: 2 additions & 0 deletions src/components/messages/message-content/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { generateMessageList } from '@/mock/data'
import MessageItem from './message-item'
import InfiniteScroll from '@/components/infinite-scroll'
// import VirtualList from '@/components/virtualizer-list/virtual-list'

const MessageContent = () => {
const parentRef = useRef<HTMLDivElement>(null)
Expand Down Expand Up @@ -88,6 +89,7 @@ const MessageContent = () => {
>
{data.reverse().map((_, index) => renderItem(index))}
</InfiniteScroll>
{/* <VirtualList data={data} itemHeight={50} height={height} children={renderItem} /> */}
</Flex>
)
}
Expand Down
21 changes: 21 additions & 0 deletions src/components/virtualizer-list/virtual-list.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
.virtual-container {
height: 600px;
width: 300px;
overflow-y: auto;
border: 1px solid #ccc;
position: relative;
}

.virtual-content {
position: absolute;
top: 0;
left: 0;
right: 0;
}

.virtual-item {
padding: 10px;
border-bottom: 1px solid #eee;
box-sizing: border-box;
}

51 changes: 51 additions & 0 deletions src/components/virtualizer-list/virtual-list.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// VirtualList.tsx
import React, { useRef, useState, useEffect } from 'react'
import Virtual from './virtual'
import './virtual-list.scss'

interface DataItem {
id: number
message: string
}

interface VirtualListProps<T = any> {
data: T[]
itemHeight?: number
height: number
children: (index: number) => React.ReactNode
}

const VirtualList: React.FC<VirtualListProps> = ({ data, itemHeight, height, children }) => {
const containerRef = useRef<HTMLDivElement>(null)
const [visibleData, setVisibleData] = useState<DataItem[]>([])

useEffect(() => {
if (containerRef.current) {
const virtual = new Virtual<DataItem>(containerRef.current, {
height,
itemHeight,
data,
renderItem: () => <>111</>
})
setVisibleData(virtual.visibleData)
}
// return () => {
// virtual.destroy()
// }
}, [containerRef, data, itemHeight, height, children])
// = new Virtual<DataItem>(containerRef.current, {})

return (
<div ref={containerRef}>
{visibleData.map((item, index) => {
return (
<div key={item.id} className="virtual-item">
{children(index)}
</div>
)
})}
</div>
)
}

export default VirtualList
Loading

0 comments on commit eb9099d

Please sign in to comment.