【问题标题】:React onScroll not firing反应onScroll没有触发
【发布时间】:2017-07-07 03:37:57
【问题描述】:

我有一个简单的反应组件,我为该组件设置了 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>
    )
  }
}

【问题讨论】:

标签: javascript reactjs scroll


【解决方案1】:

您需要将overflowY 的值更改为auto 或scroll。现在你没有得到滚动条,因为hidden 导致浏览器隐藏滚动条。

【讨论】:

  • 这个错误的一般解决方案,谢谢先生,我有溢出:隐藏在
【解决方案2】:

你需要给 DOM 元素添加一个 ref:

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);
    }
    /* .... */
}

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

    • 这不是真的。如果你想访问类this 对象,你只需要绑定处理函数。 OP 只是调用console.log,所以在这种情况下无关紧要。
    • 不是这样,this._handlescroll 对 eventHandler 没有任何意义,需要绑定!
    猜你喜欢
    • 2018-10-18
    • 2022-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多