React —父元素的onScroll侦听器?

Kir*_*oss 6 reactjs

如何在组件中添加onScroll侦听器以捕获父元素的滚动?

class ChildDiv extends React.Component {
  constructor() {
    super();
  }
  handleScrollOfParent() {
    // do stuff when parent <main> scrolls;
  }
  render() {
    return (
      <div id="child" onScroll={this.handleScrollOfParent.bind(this)}>
        // content with overflow: hidden and scroll handled by parent MAIN.
      </div>
    )
  }
}
export default ChildDiv;
Run Code Online (Sandbox Code Playgroud)

像这样在父主渲染中渲染,<main><ChildDiv /></main>我想捕捉主滚动。

Igo*_*vee 1

您可以在父组件中定义一个状态变量,该变量将存储当前的scrollTop值(假设垂直滚动)并在每次事件scroll发生时更新,然后将此变量传递给ChildDiv可以检测到该变量已更改的 componentWillReceiveProps

if(this.props.yourVariable != nextProps.yourVariable){
// scroll event was fired => scroll position changed
}
Run Code Online (Sandbox Code Playgroud)