如何根据滚动位置触发React应用中的动画

时间:2017-05-13 07:35:38

标签: reactjs scroll

假设我需要在用户滚动浏览网站标题时向导航栏添加元素。如何在不使用jQuery的情况下在React中执行类似的操作?

1 个答案:

答案 0 :(得分:3)

你可以做这样的事情:( 这个函数是从我之前创建的react-sticky-dynamic-header复制的https://github.com/thinhvo0108/react-sticky-dynamic-header

componentDidMount() {
    var h1 = parseInt(this.refs.header.offsetHeight);
    window.addEventListener('scroll', this._calcScroll.bind(this, h1));
}

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

_calcScroll(h1) {
    var _window = window;
    var heightDiff = parseInt(h1);
    var scrollPos = _window.scrollY;
    if (scrollPos > heightDiff) {
        // here this means user has scrolled past your header, 
        // you may rerender by setting State or do whatever
        this.setState({
            //stateKey: stateValue,
        });
    } else {
        // here the user has scrolled back to header's territory, 
        // it's optional here for you to remove the element on navbar as stated in the question or not
        this.setState({
            //stateKey: stateValue,
        });
    }
}

render() {
  return (
    <div ref="header">YOUR HEADER HERE</div>
  );
}

对于在导航栏中添加或删除元素时的平滑动画,您只需将其添加到元素的CSS样式中即可:

#your-element{
  transition: opacity 0.3s ease-in;
}

您可以尝试安装我的库以查看它是否可以扩展您的需求:

https://www.npmjs.com/package/react-sticky-dynamic-header

如果有的话,请随时在此处发布一些错误,谢谢