前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >react虚拟滚动的实现

react虚拟滚动的实现

作者头像
theanarkh
发布2019-12-23 17:58:10
1.6K0
发布2019-12-23 17:58:10
举报
文章被收录于专栏:原创分享原创分享

github地址https://github.com/theanarkh/react-virtual-scroll

代码语言:javascript
复制
import ReactDOM from 'react-dom'
import React, { useState, useMemo } from 'react'

function getData(length = 10000) {
  const arr = []
  var i = 0
  while (i < length) {
    arr.push(String(i++))
  }
  return arr
}
const data = getData()
const itemHeight = 21
const itemLength = 10
// 是否开启虚拟滚动
const enableVirtualScroll = true

export default function App() {
  let [list, setList] = useState(data)
  const [offset, setOffset] = useState(0)
  const [scroll, setScroll] = useState(0)
  const options = useMemo(() => {
    return list.length ? list.slice(offset, offset + itemLength) : ['暂无数据']
  }, [offset, list])
  return (
    <>
      <input
        onChange={v => {
          const next = data.filter(value => {
            return value.includes(v.target.value)
          })
          setList(next)
        }}
      />
      <div
        onScroll={event => {
          if (!enableVirtualScroll) {
            return
          }
          var { scrollTop } = event.target
          setScroll(scrollTop)
          setOffset(~~(scrollTop / itemHeight))
        }}
        style={{
          height: `${options.length > itemLength ? itemHeight * itemLength : options.length * itemHeight}px`,
          overflowY: 'scroll',
          border: '1px solid black',
          marginTop: '10px'
        }}>
        <ul style={{ height: `${list.length * itemHeight}px`, position: 'relative', listStyleType: 'none', margin: '0px' }}>
          {(enableVirtualScroll ? options : list).map((v, index) => {
            return (
              <li style={enableVirtualScroll ? { position: 'absolute', top: `${index * itemHeight + scroll}px` } : {}} key={index}>
                {v}
              </li>
)
          })}
        </ul>
      </div>
    </>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-12-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 编程杂技 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档