我有一个使用滚动事件的 React 组件。当调用滚动事件时,它基本上按预期运行处理程序。但是,当滚动事件开始触发时,我需要能够调用一次方法。我理解在滚动停止时触发的去抖动方法的想法,但我需要找到一种在滚动开始时触发一次的方法。 (当然不能使用 jQuery)。
componentDidMount() {
window.addEventListener('scroll', this.onScroll);
this.setState({
// sets some state which is compared in a shouldComponentUpdate
});
}
componentWillUnmount() {
window.removeEventListener('scroll', this.onScroll);
}
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
下面看到的处理程序运行一些代码:
onScroll() {
this.scrollTop = document.documentElement.scrollTop;
this.update();
}
但我需要一个运行一次的函数:
scrollStart() {
}
我很想说我已经尝试过一些东西,但不幸的是我没有想法。任何帮助将不胜感激。
最佳答案
浏览器中没有真正的滚动状态;滚动事件发生,然后结束。
例如,您可以每次用户滚动时创建一个新的超时,如果用户在超时函数运行之前没有滚动,则将您自己的滚动状态设置为 false。
示例
class App extends React.Component {
timeout = null;
state = { isScrolling: false };
componentDidMount() {
window.addEventListener("scroll", this.onScroll);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.onScroll);
}
onScroll = () => {
clearTimeout(this.timeout);
const { isScrolling } = this.state;
if (!isScrolling) {
this.setState({ isScrolling: true });
}
this.timeout = setTimeout(() => {
this.setState({ isScrolling: false });
}, 200);
};
render() {
return (
<div
style={{
width: 200,
height: 1000,
background: this.state.isScrolling ? "green" : "red"
}}
/>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于javascript - 滚动开始时调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51522045/