使用stopPropagation()处理React事件委托 [英] Handle React event delegation with stopPropagation()

查看:583
本文介绍了使用stopPropagation()处理React事件委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React有一个项目,应该可以放在任何网站上。我的想法是我托管一个javascript文件,人们放置一个具有特定ID的div,并且React在该div中呈现。

I have a project in React which should be able to be placed on any website. The idea is that I host a javascript file, people place a div with a specific ID, and React renders in that div.

到目前为止这是有效的,除了点击事件。这些平均值在顶层处理。这一切都很好,但是应该放置应用程序的站点之一,为非画布菜单实现了 stopPropagation()。因此,事件无法正常工作。

So far this works, except click-events. These evens are handled at the top level. This is all good, but one of the sites where the app should be placed, has stopPropagation() implemented for a off-canvas menu. Because of this the events aren't working properly.

我尝试在root元素上捕获所有事件,并手动调度它们:

I tried catching all events at the root-element, and dispatching them manually:

this.refs.wrapper.addEventListener('click', (event) => {
    console.log(event);
    console.log(event.type);
    const evt = event || window.event;
    evt.preventDefault();
    evt.stopImmediatePropagation();
    if (evt.stopPropagation) evt.stopPropagation();
    if (evt.cancelBubble !== null) evt.cancelBubble = true;
    document.dispatchEvent(event);
});

这不起作用,因为事件已经被派遣:

This doesn't work, because the event is already being dispatched:

未捕获的InvalidStateError:无法在'EventTarget'上执行'dispatchEvent':事件已被调度。

解决这个问题的正确方法是什么?不使用React的合成事件似乎不适合我..

What would be the right way to fix this problem? Not using the synthetic events from React doesn't seem the right way to go for me..

推荐答案

参数'event h'已经派出。
你应该用旧事件克隆一个新的eventobject。

Argument 'event h'as already been dispatched. You should clone a new eventobject with old event.

var newevent = new event.constructor(event.type, event)

这篇关于使用stopPropagation()处理React事件委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆