A working example of infinite scroll on a table element. Also a working a repl.
import React, {useState, useEffect} from 'react';
import './App.css';
function App() {
let items = [];
for (let i = 0; i < 100; i++) {
items.push({
key: 'foo' + i,
value: 'bar' + i,
});
}
let dataTable = React.createRef();
const [list, setList] = useState({
itemsDisplayed: 20,
data: items.slice(0, 20),
});
let onScroll = () => {
let tableEl = dataTable.current;
if (tableEl.scrollTop === (tableEl.scrollHeight - tableEl.offsetHeight)) {
if (list.itemsDisplayed + 10 <= items.length) {
setList({
itemsDisplayed: list.itemsDisplayed + 10,
data: items.slice(0, list.itemsDisplayed + 10),
});
}
}
};
return (
<div className="App">
<table id="data-table" ref={dataTable} onScroll={onScroll}>
<tbody>
{list.data.map((item) => {
return (
<tr key={item.key}>
{item.value}
</tr>
);
})}
</tbody>
</table>
</div>
);
}
export default App;
Also to mention, the problem of scrolling firing only once solved by this question. The point is to use React's built-in onScroll event.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…