hooks icon indicating copy to clipboard operation
hooks copied to clipboard

useEventListener target为null,默认全局绑定事件

Open MaloWang opened this issue 1 year ago • 5 comments

portal A,内包子页面B, 有元素类名为 'testclass', 应用A,'test-id'绑定click事件, useEventListener( 'click', (e) => { if (e.target.className === 'testclass') { do... } }, { target: document.getElementById('test-id') }, ); 这时候页面B展示的时候逻辑正常。

当,portal A 内如果展示的是子页面C,document.getElementById('test-id') 为null, 这时候会默认全局绑定了click事件。页面C里元素如果有相同类名'testclass',就会触发本不应该触发的逻辑。

期望如果target为null的时候,不要默认在body上绑定事件

MaloWang avatar Jun 18 '24 03:06 MaloWang

投反对修改一票

q1557050025 avatar Jun 26 '24 07:06 q1557050025

我也投反对 @MaloWang 那你 觉得绑哪里呢?

crazylxr avatar Jul 16 '24 01:07 crazylxr

我也遇到了个相同的问题,用useRef引用dom,然后作为target参数,会导致第一次是监听在保底的window上。如果我上了mousemove这种触发频率比较大的事件,会导致第一次handler触发并不是我想要的。我觉得可以改个判断options里有target的key,就默认不走保底挂载window上

apades avatar Aug 09 '24 14:08 apades

懂了,最近意识到这个问题了,可能需要加个参数来决定是否走默认的

crazylxr avatar Aug 23 '24 07:08 crazylxr

懂了,最近意识到这个问题了,可能需要加个参数来决定是否走默认的

当时因为这个造成了有点严重的线上bug,希望尽快解决

wangyiye avatar Oct 09 '24 13:10 wangyiye