e.nativeEvent.stopPropagation()}>我是弹窗\n )}\n \n );\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"从上面的代码里我们不难看出我们想要做一个点击某一个按钮来展示一个模态框,并且在点击除了模态框区域以外的位置希望能够关闭这个模态框。 但是实际运行结果和我们所想的完全不一样,点击了button按钮并没有任何反应,这就需要从"},{"type":"codeinline","content":[{"type":"text","text":"React"}]},{"type":"text","text":"的合成事件说起了,让我们分析完"},{"type":"codeinline","content":[{"type":"text","text":"React"}]},{"type":"text","text":"的合成事件 后能够完全的来解答这个问题。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"demo地址:https:\/\/codesandbox.io\/s\/event-uww15?file=\/src\/App.tsx:0-690"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"合成事件的特性"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"React"}]},{"type":"text","text":"自行实现了一套事件系统,主要特性有以下"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":null,"normalizeStart":1},"content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"自行实现了一套事件捕获到事件冒泡的逻辑, 抹平各个浏览器之前的兼容性问题。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"使用对象池来管理合成事件对象的创建和销毁,可以减少垃圾回收次数,防止内存抖动。"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"事件只在document上绑定,并且每种事件只绑定一次,减少内存开销。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先我们先抛开上面那个按钮,用下面这个十分简单的案例来了解"},{"type":"codeinline","content":[{"type":"text","text":"React"}]},{"type":"text","text":"的事件使用。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"function App() {\n function handleButtonLog(e: React.MouseEvent
) {\n console.log(e.currentTarget);\n }\n function handleDivLog(e: React.MouseEvent) {\n console.log(e.currentTarget);\n }\n function handleH1Log(e: React.MouseEvent) {\n console.log(e.currentTarget);\n }\n return (\n \n
\n