React JS滚动优化

疯狂的麦克斯

我在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函数触发的次数过多。所以我的问题是如何优化此代码?

凯尔·理查森(Kyle Richardson)

尝试对该handleScroll方法进行此修改

handleScroll = () => {
    if(!this.contentRef) return;

    const navShouldBeFixed = window.scrollY >= this.contentRef.offsetTop - 32

    if(this.state.navigationFixed && !navShouldBeFixed) {
        this.setState({navigationFixed: false});
    } else if (!this.state.navigationFixed && navShouldBeFixed) {
        this.setState({navShouldBeFixed: true})
    }
}

编辑:更少的代码行。

handleScroll = () => {
    if(!this.contentRef) return;

    const navShouldBeFixed = window.scrollY >= this.contentRef.offsetTop - 32

    if(this.state.navigationFixed && !navShouldBeFixed || 
       !this.state.navigationFixed && navShouldBeFixed) {
        this.setState({navigationFixed: navShouldBeFixed});
    }
}

这样,setState仅在需要更改UI时才触发方法。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章