根据IE上的滚动位置更改状态

时间:2018-08-16 23:46:30

标签: reactjs internet-explorer

我需要按滚动位置向div添加或删除一个类。所以我在文档滚动事件中添加了一个侦听器以更改状态

componentDidMount() {
    document.addEventListener('scroll', function (event) {
      const isPassedTop = window.pageYOffset  > 100;
      if (isPassedTop !== this.state.isPassedTop) {
        this.setState({ isPassedTop: isPassedTop })
      }
    }, true);
}

此代码在chrome上有效,但是在IE上说对象不支持属性或方法“ setState” 我可以使用jquery在其中添加或删除一个类,但是我正在寻找一种按状态执行的方法。 任何人都知道如何在跨浏览器上做到这一点?

1 个答案:

答案 0 :(得分:1)

执行此操作的最佳方法是创建一个绑定函数,以便以后可以引用它以在卸载时删除侦听器,如下所示:

class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleScrollChange = this.handleScrollChange.bind(this);
  }    

  handleScrollChange() {
    const isPassedTop = window.pageYOffset  > 100;
    if (isPassedTop !== this.state.isPassedTop) {
      this.setState({ isPassedTop: isPassedTop })
    }
  }

  componentDidMount() {
    document.addEventListener('scroll', this.handleScrollChange, true);
  }

  componentWillUnmount() {
    document.removeEventListener('scroll', this.handleScrollChange);
  }
}
相关问题