UNPKG

fanyucomponents

Version:

一款以 純邏輯為核心、無樣式綁定 的 React 元件套件

25 lines (24 loc) 847 B
import React from "react"; /** * 攔截指定的事件並自動 stopPropagation * @param child React element * @returns React element */ export const withStopPropagation = (child) => { if (!React.isValidElement(child)) return child; const newProps = {}; for (const [key, value] of Object.entries(child.props || {})) { if (key.startsWith("on") && typeof value === "function") { newProps[key] = (...args) => { const event = args[0]; if ((event === null || event === void 0 ? void 0 : event.stopPropagation) instanceof Function) { event.stopPropagation(); console.log(key, "有處理到事件冒泡"); } value(...args); }; } } return React.cloneElement(child, newProps); };