如何在滚动时显示 React 组件 [英] How to reveal a React component on scroll

查看:56
本文介绍了如何在滚动时显示 React 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为固定导航创建了一个 React 组件,我希望将其保持隐藏状态,直到我滚动经过页面上的某个点,然后滑入视图.Medium 的标头与我所描述的类似.

I've created a React component for a fixed nav that I would like to remain hidden, until I scroll past a certain point on the page, then slides into view. Medium has a header similar to what I'm describing.

这是jQuery,带有 scrollmagic 或航路点,但是否有一种惯用的方法可以使用 React 和 vanilla JS 来实现这一点?

This is a relatively trivial task in jQuery, with scrollmagic or waypoints but is there an idiomatic way of accomplishing this with React and vanilla JS?

推荐答案

React Way with vanilla JS jsfiddle;

React Way with vanilla JS jsfiddle;

不要忘记删除 EventListener.在此示例中,组件将在必要时呈现

don't forget to remove EventListener. In this example component will render if only it is neccessary

class TopBar extends React.Component {
    state = { isHide: false };

    hideBar = () => {
       const { isHide } = this.state

       window.scrollY > this.prev ?
       !isHide && this.setState({ isHide: true })
       :
       isHide && this.setState({ isHide: false });

       this.prev = window.scrollY;
    }

    componentDidMount(){
        window.addEventListener('scroll', this.hideBar);
    }

    componentWillUnmount(){
         window.removeEventListener('scroll', this.hideBar);
    }

    render(){
        const classHide = this.state.isHide ? 'hide' : '';
        return <div className={`topbar ${classHide}`}>topbar</div>;
    }
}

这篇关于如何在滚动时显示 React 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆