Reactjs 中的鼠标滚轮事件

IT技术 reactjs
2021-05-12 03:13:47

你如何在 reactjs 中获取鼠标滚轮事件?

我试过onWheel

  render: function() {
    return <div onWheel = {this.wheel} >
       < /div>;
  },

我试过 onScroll

  render: function() {
    return <div onScroll = {this.wheel} >
       < /div>;
  },

但这些事件都没有被接受。请参阅下面的小提琴:

https://jsfiddle.net/812jnppf/2/

2个回答

首先,你的 div 是 0 高度,所以你不要滚动它。您不必绑定它,因为它是一个类(而不是 es6 react组件)。只需使用该事件作为 onWheel 事件的参数调用该函数即可:

https://jsfiddle.net/812jnppf/9/

render: function() {

   return <div style={{height:300, width:300}} onWheel = {(e) => this.wheel(e)} >      < /div>;
},

当然,您必须清理代码才能使用 var 或 css 来设置 div 的样式。

编辑:我将它设置为 onWheel 而不是 onScroll(我猜女巫不存在?如果你知道,请确认)。我看到了一篇关于轻松向组件添加滚动事件的 SO 帖子:https ://stackoverflow.com/a/29726000/4099279

将回调绑定到this

render: function() {
    return <div onWheel = {this.wheel.bind(this)} >
       < /div>;
}