我正在开发一个反应组件,基本上滚动到底部进料。
我在加载更多数据和道具时遇到问题,滚动事件队列并在加载完成后执行。我已尝试在加载数据时禁用并启用滚动,如此处所述
this.keys = {37: 1, 38: 1, 39: 1, 40: 1};
preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
preventDefaultForScrollKeys(e) {
if (this.keys[e.keyCode]) {
this.preventDefault(e);
return false;
}
}
disableScroll() {
if (window.addEventListener) // older FF
window.addEventListener('DOMMouseScroll', this.preventDefault, false);
window.onwheel = this.preventDefault; // modern standard
window.onmousewheel = document.onmousewheel = this.preventDefault; // older browsers, IE
window.ontouchmove = this.preventDefault; // mobile
document.onkeydown = this.preventDefaultForScrollKeys;
}
enableScroll() {
if (window.removeEventListener)
window.removeEventListener('DOMMouseScroll', this.preventDefault, false);
window.onmousewheel = document.onmousewheel = null;
window.onwheel = null;
window.ontouchmove = null;
document.onkeydown = null;
}
ComponentDidRecieveProps(){
this.enableScroll();
}
handleScroll(event){
if((event.target.scrollTop + event.target.clientHeight) >= (event.target.scrollHeight) && event.target.scrollTop > this.lastScrollTop) {
//when hits bottom
this.disableScroll();
this.getMoreData();
}
this.lastScrollTop = event.target.scrollTop
}
render(){
return <div onScroll = {(e) => this.handleScroll(e)}> DATA </div>
}
How to disable scrolling temporarily?
事件虽然滚动禁用但是一旦我启用滚动它就会执行排队的事件,因此即使没有用户滚动也可以滚动。
我正在使用div的onScroll事件,当它到达底部时加载更多数据。
答案 0 :(得分:1)
这个怎么样?获取完成后dataLoaded = true
,并在获取新集之前将其设置为false。我还没有测试过。
import React, { PropTypes } from 'react';
class ScrollingComponent extends React.Component {
constructor(props) {
super(props);
}
removeScrollListener() {
// if running on client side
document.removeEventListener('scroll', this.handleScroll, false);
}
addScrollListener() {
// if running on client side
document.addEventListener('scroll', this.handleScroll, false);
}
ComponentDidRecieveProps({ dataLoaded }){
if(dataLoaded){
this.addScrollListener();
} else{
this.removeScrollListener()
}
}
handleScroll() {
// your logic
}
render() {
const { data, dataLoaded } = this.props;
const loading = dataLoaded ? null : <p>Loading ...</p>;
return (
<div>
<loading />
<Table>
<tbody >
// loop through your data
</tbody>
</Table>
</div>
);
}
};
const { arrayOf, bool, object } = PropTypes;
ScrollingComponent.propTypes = {
data: arrayOf(object),
dataLoaded: bool
};