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

查看:28
本文介绍了在 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 方法如下所示:

The component render method looks like this:

  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天全站免登陆