英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论