消除React组件中的视差

问题描述 投票:2回答:1

我有一个带有简单视差的React组件,它可以更改top和opacity值。 问题是滚动动画有点生涩。 有什么办法可以使过渡平滑吗? 我在香草JS中使用了requestAnimationFrame() ,但是我认为我不能在React组件中使用它,因为渲染周期不同。

另外,一旦元素离开视口,如何停止更改状态?

这是我的实现:

 const Parallax = React.createClass({ getInitialState: function () { return { top: 0, opacity: 1 }; }, parallax: function(event) { const scrollTop = window.pageYOffset; const elementHeight = this.splash.clientHeight; this.setState({ top: scrollTop * .7 + 'px' }); this.setState({ opacity: (elementHeight - scrollTop) / elementHeight }); }, componentDidMount: function() { window.addEventListener('scroll', this.parallax); }, componentWillUnmount: function() { window.removeEventListener('scroll', this.parallax); }, render: function() { const splashStyle = { transform: 'translateY(' + this.state.top +')', opacity: this.state.opacity }; return ( <div className="splash" ref={ domElement => { this.splash = domElement; }}> <div className="splash__wrapper " style={ splashStyle }> <p>LONG CONTENT</p> </div> </div> ); } }); ReactDOM.render( <Parallax />, document.getElementById('container') ); 
 .splash { position: relative; width: 100vw; max-width: 100%; height: 100vh; min-height: 500px; background: url(https://facebook.github.io/react/img/logo_og.png) no-repeat 10% 60%; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } .splash__wrapper { position: absolute; color: #fff; width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: center; transition: 0s transform; } 
 <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="container"> <!-- This element's contents will be replaced with your component. --> </div> 

更新:

Splash组件位于页面的顶部,因此我可以使用以下方法将状态更改限制为仅当元素处于可见状态时。 不能改善滚动性能。

if (scrollTop < elementHeight) {
  this.setState({ top: scrollTop * .7 + 'px' });
  this.setState({ opacity: (elementHeight - scrollTop) / elementHeight });
}
javascript css reactjs
1个回答
0
投票

用户滚动页面会触发很多滚动事件。 您不想对每个滚动事件做出反应,而是将它们分组,例如每1000毫秒一次。

这称为节流阀。 lodash库有一个不错的节流方法,但其他方法也存在。

包含lodash库后,您的事件监听器将如下所示:

window.addEventListener('scroll', _.throttle(this.parallax, 1000));
© www.soinside.com 2019 - 2024. All rights reserved.