react + antd table列表自动滚动

发布时间 2023-05-08 14:55:33作者: 凹润之之之
/**
* @file: table列表自动滚动,鼠标划入滚动暂停,鼠标划出滚动继续
*/
const [dataSource, setDataSource] = useState([])

const [timer, setTimer] = useState()

useEffect(() => {
  if (dataSource.length) {
    autoScroll(dataSource)
  }
  return () => clearInterval(timer);
}, [dataSource])

const autoScroll = (data) => {
  let v = document.getElementsByClassName('antd-table-body')[0];
  if (data.length > 5) { // 5可以根据各自的列表高度替换
    let time = setInterval(() => {
      v.scrollTop++;
      if (Math.ceil(v.scrollTop) >= parserFloat(v.scrollHeight - v.clientHeight)) { // 滚动条到底后重新开始
        v.scrollTop = 0;
      }
    }, 50)
    setTimer(timer);
  }
}

return (
  <div
    onMouseEnter={() => {
      clearInterval(timer)
    }}
    onMouseLeave={() => {
      autoScroll(dataSource)
    }}
  >
    <Table
      dataSource={dataSource}
      scroll={{ y: 320 }}
      columns={...}
    />
  </div>
)