在React.js中更新onScroll组件的样式 [英] Update style of a component onScroll in React.js

查看:99
本文介绍了在React.js中更新onScroll组件的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React中构建了一个组件,它应该在窗口滚动上更新自己的样式以创建视差效果。

I have built a component in React which is supposed to update its own style on window scroll to create a parallax effect.

组件 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不知道组件已更改,因此组件不会被重新渲染。

This doesn't work because React doesn't know that the component has changed, and therefore the component is not rerendered.

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

I've tried storing the value of itemTranslate in the state of the component, and calling setState in the scroll callback. However, this makes scrolling unusable as this is terribly slow.

有关如何执行此操作的任何建议吗?

Any suggestion on how to do this?

谢谢。

推荐答案

你应该在 componentDidMount 中绑定监听器,这样它只创建一次。您应该能够将样式存储在状态中,监听器可能是性能问题的原因。

You should bind the listener in componentDidMount, that way it's only created once. You should be able to store the style in state, the listener was probably the cause of performance issues.

这样的事情:

componentDidMount: function() {
    window.addEventListener('scroll', this.handleScroll);
},

componentWillUnmount: function() {
    window.removeEventListener('scroll', this.handleScroll);
},

handleScroll: function(event) {
    let scrollTop = event.srcElement.body.scrollTop,
        itemTranslate = Math.min(0, scrollTop/3 - 60);

    this.setState({
      transform: itemTranslate
    });
},

这篇关于在React.js中更新onScroll组件的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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