在React.js中更新组件onScroll的样式

我已经在React中构建了一个组件,该组件应该在窗口滚动时更新其自身的样式以创建视差效果。


组件render方法如下所示:


  function() {

    let style = { transform: 'translateY(0px)' };


    window.addEventListener('scroll', (event) => {

      let scrollTop = event.srcElement.body.scrollTop,

          itemTranslate = Math.min(0, scrollTop/3 - 60);


      style.transform = 'translateY(' + itemTranslate + 'px)');

    });


    return (

      <div style={style}></div>

    );

  }

这是行不通的,因为React不知道组件已更改,因此该组件不会重新渲染。


我试过itemTranslate在组件状态下存储的值,并setState在滚动回调中调用。但是,这使滚动无法使用,因为这非常慢。


关于如何做到这一点的任何建议?


蛊毒传说
浏览 773回答 3
3回答

DIEA

您应该在中绑定侦听器componentDidMount,这样,侦听器仅创建一次。您应该能够将样式存储在状态中,侦听器可能是导致性能问题的原因。像这样:componentDidMount: function() {&nbsp; &nbsp; window.addEventListener('scroll', this.handleScroll);},componentWillUnmount: function() {&nbsp; &nbsp; window.removeEventListener('scroll', this.handleScroll);},handleScroll: function(event) {&nbsp; &nbsp; let scrollTop = event.srcElement.body.scrollTop,&nbsp; &nbsp; &nbsp; &nbsp; itemTranslate = Math.min(0, scrollTop/3 - 60);&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; transform: itemTranslate&nbsp; &nbsp; });},

慕雪6442864

为了帮助这里的任何人,在使用Austins答案时注意到缓慢的行为/性能问题,并想要使用注释中提到的ref的示例,以下是我用于切换类的上/下图标的示例:在render方法中:<i ref={(ref) => this.scrollIcon = ref} className="fa fa-2x fa-chevron-down"></i>在处理程序方法中:if (this.scrollIcon !== null) {&nbsp; if(($(document).scrollTop() + $(window).height() / 2) > ($('body').height() / 2)){&nbsp; &nbsp; $(this.scrollIcon).attr('class', 'fa fa-2x fa-chevron-up');&nbsp; }else{&nbsp; &nbsp; $(this.scrollIcon).attr('class', 'fa fa-2x fa-chevron-down');&nbsp; }}并按照奥斯汀提到的方式添加/删除处理程序:componentDidMount(){&nbsp; window.addEventListener('scroll', this.handleScroll);},componentWillUnmount(){&nbsp; window.removeEventListener('scroll', this.handleScroll);},refs上的文档。

沧海一幻觉

我制作响应式导航栏的解决方案(位置:不滚动时为“相对”,滚动时且不在页面顶部时为固定)componentDidMount() {&nbsp; &nbsp; window.addEventListener('scroll', this.handleScroll);}componentWillUnmount() {&nbsp; &nbsp; window.removeEventListener('scroll', this.handleScroll);}handleScroll(event) {&nbsp; &nbsp; if (window.scrollY === 0 && this.state.scrolling === true) {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({scrolling: false});&nbsp; &nbsp; }&nbsp; &nbsp; else if (window.scrollY !== 0 && this.state.scrolling !== true) {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({scrolling: true});&nbsp; &nbsp; }}&nbsp; &nbsp; <Navbar&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; style={{color: '#06DCD6', borderWidth: 0, position: this.state.scrolling ? 'fixed' : 'relative', top: 0, width: '100vw', zIndex: 1}}&nbsp; &nbsp; &nbsp; &nbsp; >我没有任何性能问题。
打开App,查看更多内容
随时随地看视频慕课网APP