将滚动位置存储在滚动方向更改

时间:2016-08-04 17:31:28

标签: reactjs jsx

我正在处理一个反应模块,该模块根据滚动位置处理显示和隐藏状态元素。我所拥有的是功能性的,但我需要能够捕捉方向变化scroll position

以下是相关的代码片段,所有绑定和事件侦听器都可以正常运行:

this.state = {
  lastScrollPos: 0,
  down: true
};

_scrollFunction() {
  const thisPos = window.pageYOffset;
  const down = thisPos > this.state.lastScrollPos;

  if (down) {
    this.setState({
      down: true,
      lastScrollPos: thisPos
    });
  } else if (!down) {
    this.setState({
      down: false,
      lastScrollPos: thisPos
    });
  }

}

在上面的_scrollFunction()中,设置lastScrollPos: thisPos会在页面再次滚动之前给出滚动位置。

我的问题是如何捕捉滚动方向改变时的滚动位置。如果我向下滚动然后向上滚动,我需要知道它发生的位置,反之亦然。

对此有任何建议表示赞赏!谢谢!

1 个答案:

答案 0 :(得分:1)

您应该检查_scrollFunction当前down值是否与州的down值不同。如果是,请将thisPos值写入changedPos状态变量。

工作示例:

constructor() {
  super();

  this.state = {
    lastScrollPos: 0,
    changedPos: undefined,
    down: true
  };
}

_scrollFunction() {
  const thisPos = window.pageYOffset;
  const down = thisPos > this.state.lastScrollPos;
  // If current `down` value is differs from `down` from state,
  // assign `thisPos` to variable, else assigning current `changedPos` state value.
  const changedPos = down !== this.state.down ? thisPos : this.state.changedPos;

  this.setState({
    lastScrollPos: thisPos,
    changedPos,
    down
  });
}

另外,我已经在CodePen上制作了演示版,您可以查看其他信息。

相关问题