最简单的解决方案:
将scrollPosition 和containerSize 添加到this.state
在render()中的容器中创建ref
<div ref={cont => { this.scrollContainer = cont; }} />
在componentDidMount()订阅scroll事件
this.scrollContainer.addEventListener('scroll', this.handleScroll)
在componentWillUnmount()退订
this.scrollContainer.removeEventListener('scroll', this.handleScroll)
你的handleScroll应该看起来像
handleScroll (e) {
const { target: { scrollTop, clientHeight } } = e;
this.setState(state => ({...state, scrollPosition: scrollTop, containerSize: clientHeight}))
}
然后在您的渲染函数中检查应该显示哪个元素并渲染正确的元素 numOfElementsToRender = state.containerSize / elementSize 和 firstElementIndex = state.scrollPosition / elementSize - 1
当您拥有所有这些时,只需呈现您的元素列表并根据元素的index 应用过滤器,或者您想要对它们进行排序
您需要处理所有边缘情况并添加 bufor 以实现平滑滚动(高度的 20% 应该没问题)