React onScroll没有开火

时间:2017-02-17 14:50:44

标签: javascript reactjs scroll

我有简单的反应组件,我将onScroll事件设置为该组件但是当我滚动时它没有触发

import React, { Component, PropTypes } from 'react'

export default class MyComponent extends Component {
  _handleScroll(e) {
    console.log('scrolling')
  }

  render() {
    const style = {
      width: '100px',
      height: '100px',
      overflowY: 'hidden'
    }
    const innerDiv = {
      height: '300px',
      width: '100px',
      background: '#efefef'
    }
    return (
      <div style={style} onScroll={this._handleScroll}>
        <div style={innerDiv}/>
      </div>
    )
  }
}

3 个答案:

答案 0 :(得分:4)

您需要将overflowY的值更改为autoscroll。目前您还没有获得滚动条,因为hidden会导致浏览器隐藏滚动条。

答案 1 :(得分:2)

您需要在构造函数中绑定_handleScroll事件。尝试将此添加到您的组件。

constructor() {
  this._handleScroll = this._handleScroll.bind(this);
}

https://facebook.github.io/react/docs/handling-events.html

答案 2 :(得分:1)

您需要为DOM元素添加引用:

React onScroll not working

class ScrollingApp extends React.Component {

    _handleScroll(ev) {
        console.log("Scrolling!");
    }
    componentDidMount() {
        const list = ReactDOM.findDOMNode(this.refs.list)
        list.addEventListener('scroll', this._handleScroll);
    }
    componentWillUnmount() {
        const list = ReactDOM.findDOMNode(this.refs.list)
        list.removeEventListener('scroll', this._handleScroll);
    }
    /* .... */
}