如何在React中使用passive:false的事件监听器?

huangapple go评论52阅读模式
英文:

How to do passive:false event listeners in React?

问题

我需要在onWheel处理程序中执行event.preventDefault(),因为存在一种特殊的UI需求,其中鼠标滚轮会控制某个元素上的“缩放”效果。

但是React在滚轮事件上设置了passive: true,所以event.preventDefault()不起作用。

是否有一种安全的方式可以让您以某种方式手动附加事件?

我知道的唯一方法是使用引用(ref),然后在useEffect内部调用ref.current.addEventListener。我尝试过这种方法,似乎可以工作,但我认为这违反了官方建议,因为(如果我理解正确的话)如果ref.current发生变化,React将不会知道重新运行该效果。如果这种情况在实际应用中发生,那将是一个严重的错误。是否有一种更安全的方法来实现这个需求?

英文:

I need to do event.preventDefault() in an onWheel handler, because of a niche UI requirement where mousewheel will control a 'zoom' effect in a certain element.

But React sets passive: true on wheel events, so event.preventDefault() doesn't work.

Is there some escape hatch that lets you attach events manually in a safe way?

The only way I know is to use a ref and call ref.current.addEventListener within a useEffect. And I've tried that and it seems to work, but I think it goes against official advice, because (if I understand correctly) React won't know to re-run the effect if ref.current changes. And that would be a serious bug if it happens in the wild. Is there a safer way to do it?

答案1

得分: 1

你做得对。如果React没有提供相应的方法,可以使用他们提供的“逃逸口”来绕过。实际上,在此处https://react.dev/learn/manipulating-the-dom-with-refs,滚动被列为引用的有效用例之一。

引用元素不应更改,因为它由React管理。如果发生更改,将触发重新渲染,您可以在其中捕获任何更改。

英文:

You are doing it right. If React does not provide a way for you to do it, then use the "escape hatch" they provide to get around that. Infact, scrolling is listed as one of the valid use cases for refs here https://react.dev/learn/manipulating-the-dom-with-refs

The ref element should not change as it is being managed by React. And if it does, it will trigger a re-render where you can catch any changes.

huangapple
  • 本文由 发表于 2023年6月5日 20:51:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76406592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定