ReactJS:将 setState() 与 onScroll() 结合使用时出现问题

ReactJS: Issue with using setState() with onScroll()

我有一个基本固定 header -- <AppHeader> -- 以及其余内容 -- <AppMain> 的 React 应用程序。我想要做的是在滚动 window 时向 <AppHeader> 添加阴影。所以我将一个 onScroll 处理程序附加到 <AppMain> 周围的 DIV,当我检测到它滚动时,我设置了一个状态变量 scrolled,它被传递给 <AppHeader>,然后该组件可以处理添加适当的阴影 class。所以我的代码或多或少看起来像:

class App extends Component {
  _handleScroll(e) {
    console.log('scrolling:', e.target.scrollTop);
    if (e.target.scrollTop > 0) {
      this.setState({ scrolled: true });
    } else {
      this.setState({ scrolled: false });
    }
  }

  constructor(props) {
    super(props);

    this._handleScroll = this._handleScroll.bind(this);
    this.state = {
      scrolled: false
    };
  }

  render() {
    return (
      <div className="App">
        <AppHeader scrolled={this.state.scrolled} />
        <div className="AppMainScroll" onScroll={this._handleScroll}>
          <AppMain />
        </div>
      </div>
    );
  }
}

上面的代码工作得很好,当 window 滚动时,我的 <AppHeader> 获得了适当的道具值。但是,我注意到在我的控制台中 _handleScroll() 函数在滚动 div 时不断被触发,即使我没有主动滚动/与 window 交互。当我输入这个时,我在 _handleScroll() 中的 console.log() 已经发射了 2000 次,而 window 甚至不在前台。如果我一直滚动回到顶部,_handleScroll() 将不再被触发。

我在这里使用 onScrollsetState 不正确吗?

我想这就是你所缺少的。

componentDidMount() {
  window.onscroll = () => this._handleScroll()
}

_handleScroll() {
  console.log('scrolling:', document.documentElement.scrollTop);
  if (document.documentElement.scrollTop > 0) {
    this.setState({ scrolled: true });
  } else {
    this.setState({ scrolled: false });
  }
}

https://codesandbox.io/s/nk6o110464