What are synthetic events and what are primitive events

1. Composite events

Events directly bound in JSX, such as

<a onClick={(e)=> this.handleclick (e)}> update </a>Copy the code

The handleClick event here is a composite event

2. Native events

Events bound by JS native code, such as

document.body.addEventListener('click',e => {
    if(e.target&&e.target.matches('a')){
        return;
    }
    console.log('body');
});
Copy the code

Two, how to prevent the event bubbling

So far the conclusions have been drawn

  1. E.toppropagation () prevents composite events.

  2. e.nativeEvent.stopImmediatePropagation(); You can block native events on the document

  3. To prevent all bubblingevents, the only way to prevent bubblingevents is to get the DOM node listener by ref. The native event object E’s E.topPropagation () is to prevent bubblingevents (unless there are other native listener events of the dom node such as dom.addeventlister(‘click’…). )

  4. The e.target. Matches method can also be used to resolve event bubbling.

  5. If it is native click Listener, set e.propagation (), then only its own click events will be triggered. Does not even trigger its own compositing event. First principle is that the native events after the completion of execution to synthetic events, the react all synthetic events, SyntheticEvent execute callback function inside the document. The addEventListener (‘ click ‘SyntheticEvent);

IO /nancysss/ PE…

  1. E.toppropagation () prevents composite events.

Flow: Clicking the button triggers the native event on root first, then the native event on body. Next are the composite events on the document, and the native events on the document.

Because e.topPropagation () was set in the composite event, it prevented the execution of the composite event. So the output is as follows, and you can see that the out DOM composite event is not executed, and no out DOM click is printed. Success.

  1. e.nativeEvent.stopImmediatePropagation(); You can block native events on the document

  1. Dom node listener is obtained by ref, and native event object E. topPropagation() is used to prevent bubblings

  1. The e.target. Matches method can also be used to resolve event bubbling.

  1. In native Click Listener, set e.topPropagation (), that is, only its own click events will be triggered. Does not even trigger its own compositing event. React All synthetic events, syntheticEvents, perform callbacksDocument. The addEventListener (' click 'SyntheticEvent);

End: You can try it yourself. If you remove e.topPropagation () from the native listener, click button to see what the console output will be

The answer: