【问题标题】:ReactJS - How to add in a removeEventListener when my mouse enters div element (onMouseEnter)ReactJS - 当我的鼠标进入 div 元素时如何添加 removeEventListener (onMouseEnter)
【发布时间】:2020-06-27 05:28:59
【问题描述】:

问题:我怎样才能让 onMouseEnter 和 onMouseLeave 禁用然后重新启用 onScroll 功能?

我有一个 onScroll 事件监听器来监听当前页面的位置。我的问题是我有一个可以滚动的子 div 元素。

鉴于我的 onScroll 事件绑定到父 div 元素,当我打开子元素并滚动它时,我会收到未定义的 setState 错误。

当我将鼠标悬停在子 div 元素上时,我想尝试禁用 onScroll 事件侦听器。

我的代码(解释我的问题非常简单):

componentDidMount() {
    window.onscroll = () => this.listenToScroll()
}
listenToScroll() {
    // Does stuff with the value
}

render () {
    return (

        // This is the parent div element, which has a lot more text to cause the scroll effect
        <div onScroll={this.listenToScroll} >

        // This child element when clicked and expanded upon has an inner scroll element
        // When I scroll through the child element, I get a setState undefined error.
        <div>
            <ScrollExample 
                // This is what I want to happen, where when I enter this div element, the scroll event is disabled
                // When I exit it, it is re-enabled
                onMouseEnter={window.removeEventListener(this.listenToScroll, false)} 
                onMouseLeave={window.removeEventListener(this.listenToScroll, true)} 
            />
       </div>
       </div>
)

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    试试这个:

    componentDidMount() {
        window.addEventListener('scroll', this.listenToScroll)
    }
    listenToScroll() {
        // Does stuff with the value
    }
    
    render () {
        return (
    
            // This is the parent div element, which has a lot more text to cause the scroll effect
            <div onScroll={this.listenToScroll} >
    
            // This child element when clicked and expanded upon has an inner scroll element
            // When I scroll through the child element, I get a setState undefined error.
            <div>
                <ScrollExample 
                    // This is what I want to happen, where when I enter this div element, the scroll event is disabled
                    // When I exit it, it is re-enabled
                    onMouseEnter={() => window.removeEventListener('scroll', this.listenToScroll)} 
                    onMouseLeave={() => window.addEventListener('scroll', this.listenToScroll)} 
                />
           </div>
           </div>
    )
    

    【讨论】:

    • 完美运行!谢谢你的约翰尼。
    猜你喜欢
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-12
    相关资源
    最近更新 更多