Understanding React's Synthetic Event System

后端 未结 1 1899
没有蜡笔的小新
没有蜡笔的小新 2021-02-14 03:42

This has been on my mind for a few days now.

As per the docs, React has synthetic event system, which is a a cross-browser wrapper around the browser\'s native eve

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 04:31

    Alright, you perhaps already figured everything on your own, but as I asked myself the same questions, I figured I'd leave this here in case someone else is curious about not only using React but also getting an idea about how it works.

    So, I'm not entirely sure about your question (especially the "append the event to element" part) but:

    • React is all about the virtual DOM. As the name implies, it is therefore built on top of the "real" environment that is the DOM. Consequently, everything takes place in that abstracted layer, including event handling.
    • Events appear in their "natural" environment, so the DOM or native (depending on the flavor of react you are using)

    Consequently, you first need to bring the events up to the virtual DOM, compute your changes there and dispatch them to the representation of components in the virtual DOM, then bring the relevant changes back down to be reflected in the DOM appropriately.

    Carrying changes up to the virtual DOM is effectively done by top-level delegation. This means that React itself listens to all events at a document level. This also means that technically, all your events go through one capture + bubbling loop before even entering the React-specific code. I would not be able to say what that implies performance wise, because you do "lose" the time associated to that first DOM traversal, but on the other hand you will do all your changes in the virtual DOM, which is faster than doing them in the real DOM...

    Finally, SyntheticEvent is indeed a wrapper, which aims at reducing cross-browser compatibility issues. It also introduces pooling, which makes the thing faster by reducing garbage collection time. Besides, as one native event can generate several SyntheticEvent, it technically lets you create new ones easily (like a syntheticTap event that could be emitted if you receive a native touchStart then a native touchEnd in succession).

    I have written a post with more details here. It is far from perfect and their might be some imprecision, but it can perhaps give you some more info on the topic.

    0 讨论(0)
提交回复
热议问题