30

浅谈 react 基本合成事件类

 4 years ago
source link: https://www.tuicool.com/articles/Aj6N7jv
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

大家都知道 React 实现了自己的一套事件系统,今天就来说说这套事件系统的底层事件基类 SyntheticEvent ,它位于 events package 下。

qa6Jzie.png!web

下面是 Interface ,它挂载在  SyntheticEvent 作为其静态属性,其他子类主要是通过 Interface 来生成扩展自己特有的属性:

NzI3qeu.png!web

紧接着就是在原型上挂载 preventDefaultstopPropagationpresistisPersistentdestructor 等方法以及属性:

3q2u6rM.png!web

上面提到了 react 为了提升性能,在实现了一个 事件池 的概念,这样被释放的事件就可以被放入其中,下次再使用时,直接从其中取,省去了在此创建和销毁的开销:

Un63yir.png!web

此外,大家知道,不同的事件有不同的属于其本身的属性,如鼠标事件有 pageX/pageY ,滚轮事件有 deltaX/deltaY 等,上面的构造函数只是确定了基本的事件属性。所以 SyntheticEvent 实现了一个静态方法—— extend 用于扩展该事件类。

VFRRFfq.png!web

下面就看下它是如何扩展鼠标事件的:

VVr2Av7.png!web

以上只是了解了 react 事件的一小块,它将所有的事件都委托在 document 上,更多内容有兴趣的看下这篇文章 React事件机制 - 源码概览(上) ,如有不当,欢迎指出交流 :smile::smile:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK