React Process events and compose events

Divine: Explore React composite events

A concept,

Synthetic events are cross-browser wrappers for the browser’s native events. In addition to being compatible with all browsers, it has the same interface as browser native events, including stopPropagation() and preventDefault(); When you need to use the browser’s underlying event, you just need to use the nativeEvent property to get it.

// React all events are synthesized events, such as onClick,
// The corresponding native DOM event can be obtained through e.ativeEvent
const button = <button onClick={(e)= > { console.log(e.nativeEvent) }}>button</button>
Copy the code

Second, the purpose of

  1. Browser compatibility, to achieve better cross-platform
  2. Avoid garbage collection
  3. Facilitate unified event management and transaction mechanisms

You need to understand native DOM event handling mechanisms and event delegates/proxies

React binds all listening events to document to ensure bubble consistency and cross-browser execution. It uses composite events to simulate and smooth out differences between objects in different browsers.

Event objects are frequently created and reclaimed, so the event pool is introduced to obtain and release objects from the event pool (that is, React events are not released, but stored in an array. When events are triggered, events are ejected from the array of the corresponding event pool to avoid frequent creation and destruction, that is, garbage collection).

Event registration: During component generation, all vurtral DOM listener events are registered in the Document listener. That is, all event handlers are stored in the listenerBank and indexed by key (benefit: separate events that may be triggered).

Unified event monitoring, handling events in the bubbling stage, when hanging or uninstalling components, only need to add or delete objects in the unified event monitoring location, greatly improving efficiency; When the event is triggered, the component generates a composite event and passes it to document, which is distributed through the Dispatch Event callback function to execute event listening functions of the same type in the Dispatch Listener in turn.

Differences between synthesized events and native DOM events

  1. Named after a different
  2. Different types of handler function calls
  3. The default blocking behavior is different
// React Synthesizes events
// 1. Composite event names are small humps, such as onClick
<div onClick={
    // 2. The synthesized event is called as a function
    (e) = > {
        console.log("Synthetic event execution function");
        // 3. Prevent the default action function from executing the statement with event.preventdefault ()
        e.preventDefault();
    }
}>
    content
</div>
Copy the code
<! -- Native DOM event -->
<! -- 1. Name the event in all lowercase, such as onclick -->
<! -- 2. Call execution as string -->
<div onclick="handleClick()">content</div>
<a href="" onclick="console.log("Click on theaTag behavior ");return false;" >content</a>

<script>
    const handleClick = () = > {
        // 3. Prevent the default action function from executing the statement by returning false
        return false;
    }
</script>
Copy the code

Summary of differences:

Addition, Native events The React event
Event name Naming method All lowercase names (onclick, onblur) The name is small hump (onClick, onBlur)
Event handler syntax string function
Block the default behavior Event to returnfalse usee.preventDefault()methods

Fourth, the execution sequence of composite events and native events

In React, composite events are bound to the top-level document in the form of event delegates and are automatically destroyed during the component unmount phase

// The actual DOM element 'Child' is clicked in the following sequence
const MyComp = () = > {
    useEffect(() = > {
        document.addEventListener("click".() = > {
            console.log("document click")})document.getElementById("father").addEventListener("click".() = > {
            console.log("Native DOM: father click")})document.getElementById("child").addEventListener("click".() = > {
            console.log("Native DOM: Child Click")})}, [])return (
        <div id="father" onClick={()= >{console.log(" synthetic event: father onClick")}}> father<div id="child" onClick={()= >{console.log(" Synthetic event: Child onClick")}}> Child</div>
        </div>)}Copy the code

  1. React events all React events are synthetic events bound todocumentOn the element
  2. When the real DOM element is triggered, it bubbles up to the top-level elementdocumentIn the bubbling process, the corresponding native DOM listening events are executed in the bubbling orderdocumentAfter the top-level element, the corresponding composite events are executed in the order in which DOM bubbles are triggered
  3. The last executiondocuemntThe element itself mounts a listener execution function