简体   繁体   中英

Clone an instance of react's synthetic event

With vanilla JS it is possible to clone an event instance like so:

const cloneEvent = event => new event.constructor(event.type, event);

Which can be used to forward event event from one DOM element to another. For example,

const buttonA = document.querySelector('#a');
const buttonB = document.querySelector('#a');

const clickHandler = (type, forwardTo) => event => {
  console.log(type, 'was clicked');
  if (forwardTo) forwardTo.dispatchEvent(cloneEvent(event));
};

buttonA.addEventListener('click', clickHandler('A', buttonB));
buttonA.addEventListener('click', clickHandler('B'));

When you click on A you will also see 2 loggings for both buttons.

I would like to achieve the same with React's SyntheticEvent but I am running to issues presumably because SyntheticEvent have a different way of instantiation than native events. Here's a live demo that illustrates the problem: https://jsfiddle.net/2Lhsfceu/2/ (see the dev console logs)

My current solution is to clone the native event ( SyntheticEvent.nativeEvent ) as follows (updated and working live demo: https://jsfiddle.net/2Lhsfceu/1/ )

const cloneEvent = event => {
  const nativeEvent = event.nativeEvent || event;
  new nativeEvent.constructor(nativeEvent.type, nativeEvent);
}

I am wondering if there's a cleaner way or if this is the best we can do?

My concern is that by cloning only the native event the code base is dealing with two different types of events: the SyntheticEvent dispatched by the source event (coming from React) and the native event from forwarding.

As soon as dispatching the native event on the DOM is exactly like scrolling manually, it should be fine.

My concern is that by cloning only the native event the code base is dealing with two different types of events: the SyntheticEvent dispatched by the source event (coming from React) and the native event from forwarding.

What React does is that it listens to all native events on the root (the <div id="#root"/> here, they get there through bubbling), then each time it receives one it creates an equivalent SyntheticEvent that gets passed in the React code.

So if you fire native events manually, React will create their SyntheticEvent equivalent as usual, and it should be fine.

On very rare occasions, dispatching an event manually in Javascript will have a different effect than having a real user trigger the event. See this example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM