我在React组件中使用onscroll事件,代码如下:
import React, { Component } from 'react';
import throttle from 'lodash/throttle';
class Example extends Component {
state = {
navigationFixed: false,
}
componentDidMount() {
window.addEventListener('scroll', this.throttledHandleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.throttledHandleScroll);
}
handleScroll = () => {
this.contentRef && this.setState({
navigationFixed: window.scrollY >= this.contentRef.offsetTop - 32,
});
throttledHandleScroll = throttle(this.handleScroll, 80); // Using lodash throttle here
render() {
//Some variables and components here
...
<section
className={cx(s.content, {
[s.navigationFixed]: this.state.navigationFixed,
})}
id="content"
ref={(ref) => {this.contentRef = ref}}
>
...
//Another components here
</section>
}
};
这段代码可以正常工作,但有时会冻结,我猜测是因为handleScroll函数触发太频繁了。那么我的问题是如何优化这段代码?