Comparison of React synthetic events and JavaScript native events

Below we compare React synthetic events and JavaScript native events from 4 aspects.

1. Event propagation and prevention of event propagation The propagation of
browser native DOM events can be divided into 3 stages: event capture stage, where the target object inserts the event handler
call of the code piece itself, and event bubbling.
Insert picture description here

Event capture will first call the event listener bound on the outermost element of the structure tree, and then
call it inward, until the event listener on the target element is called. You can
register a capture event handler for element e when the third parameter of e.addEventListener() is set to true, and call it in the first stage of event propagation.

In addition, event capture is not a universal technology and cannot be used in browsers lower than IE9. Event bubbling is the
opposite of the performance of event capture. It will propagate events from the target element outward, from the inside out to the outermost layer.
It can be seen that event capture is of little significance in program development, and the more fatal issue is its compatibility. Therefore, React
's synthetic event does not implement event capture 仅仅支持了事件冒泡机制. This API design method is unified and concise, in
line with the "28 Principles".
To prevent the propagation of native events, you need to use e.preventDefault(), but for browsers that do not support this method (below IE9
), you can only use e.preventDefault()用 e.cancelBubble = true 来阻止。

In React synthetic events, you only need to use e.preventDefault().


What is a synthetic event :

Virtual DOM 在内存中是以对象的形式存在的,如果想要在这些对象上添加事件,就会非常
简单。React 基于 Virtual DOM 实现了一个 SyntheticEvent (合成事件)层,我们所定义的事件
处理器会接收到一个 SyntheticEvent 对象的实例,它完全符合 W3C 标准,不会存在任何 IE 标
准的兼容性问题。并且与原生的浏览器事件一样拥有同样的接口,同样支持事件的冒泡机制,我
们可以使用 stopPropagation()preventDefault() 来中断它。
所有事件都自动绑定到最外层上。如果需要访问原生事件对象,可以使用 nativeEvent 属性。
  1. Event Types The event types of
    React synthetic events are a subset of JavaScript's native event types.

  2. Event binding method

受到 DOM 标准的影响,绑定浏览器原生事件的方式也有很多种,具体如下所示。
 直接在 DOM 元素中绑定:
<button onclick="alert(1);">Test</button>  在 JavaScript 中,通过为元素的事件属性赋值的方式实现绑定:
el.onclick = e => {
    
     console.log(e); }
 通过事件监听函数来实现绑定:
el.addEventListener('click', () => {
    
    }, false);
el.attachEvent('onclick', () => {
    
    });
**相比而言,React 合成事件的绑定方式则简单得多:**
<button onClick={
    
    this.handleClick}>Test</button>

4. Event Objects
Native DOM event objects are different under W3C standards and IE standards. In the low version of the IE browser, you can
use window.eventto get the event object. In the React synthetic event system, there is no such compatibility problem, and
a synthetic event object can be obtained in the event processing function.

Guess you like

Origin blog.csdn.net/weixin_45416217/article/details/112709956