在事件事件冒泡中使用e.preventDefault取消轮事件

时间:2019-08-05 12:29:22

标签: reactjs scrollbar dom-events mousewheel

我正在尝试防止在触发wheel事件时使用e.preventDefault()滚动窗口,但是无论如何浏览器都滚动。

<div onWheel={this.handleWheelEvent} >
  <div className='yellow fullpage'>Yellow Page</div>
  <div className='green fullpage'>Green Page</div>
  <div className='blue fullpage'>Yellow Page</div>
</div>

js

handleWheelEvent = e => {
    e.preventDefault();
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
    // those 3 should prevent browser from scrolling but they don't
}

3 个答案:

答案 0 :(得分:1)

React 在根元素(不是 document)绑定所有事件,wheel 事件是使用 true option 在内部绑定的,我引用 MDN:< /p> <块引用>

一个布尔值,如果为真,则表示侦听器指定的函数永远不会调用 preventDefault()。如果被动侦听器确实调用了 preventDefault(),则用户代理除了生成控制台警告外不会执行任何操作

这就是我在使用滚轮影响输入字段时阻止页面滚动的方式:

const wheelTimeout = useRef()

const onWheel = e => {
    // ... some code I needed ...

    // while wheel is moving, do not release the lock
    clearTimeout(wheelTimeout.current)

    // flag indicating to lock page scrolling (setTimeout returns a number)
    wheelTimeout.current = setTimeout(() => {
      wheelTimeout.current = false
    }, 300)
}

// block the body from scrolling (or any other element)
useEffect(() => {
    const cancelWheel = e => wheelTimeout.current && e.preventDefault()
    document.body.addEventListener('wheel', cancelWheel, {passive:false})
    return () => document.body.removeEventListener('wheel', cancelWheel)
}, [])

参考讨论:

答案 1 :(得分:0)

我找不到防止在React事件中滚动的方法,但可以使用refs达到相同的效果

在构造函数中:

this.divRef = React.createRef()
this.preventDefault = e => e.preventDefault()

渲染中:

<div ref={this.divRef} >
  <div className='yellow fullpage'>Yellow Page</div>
  <div className='green fullpage'>Green Page</div>
  <div className='blue fullpage'>Yellow Page</div>
</div>

添加和删除preventDefault事件侦听器:

componentDidMount () {
    this.divRef.current.addEventListener('wheel', this.preventDefault)
}

componentWillUnmount () {
    this.divRef.current.removeEventListener('wheel', this.preventDefault)
}

答案 2 :(得分:0)

<div onWheel={e => e.stopPropagation()}></div>

尝试