iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0
JavaScript

React30——用 React 探索 JavaScript30 的魅力系列 第 25

[Day25]_Event-Capture-Propagation-Bubbling-and-Once

  • 分享至 

  • xImage
  •  

Day25 主要聚焦於 JavaScript 中的各種事件處理,就讓我們寫個按鈕與互動畫面來觀察ㄅ

資料

const colorMap: ColorMapType = {
  OUTER: "text-yellow-500",
  MIDDLE: "text-blue-500",
  INNER: "text-green-500",
  BUTTON: "text-red-500",
};

const getColor = (name: string): string => colorMap[name] || "text-gray-500";

  const [log, setLog] = useState<LogEntryType[]>([]);

功能函式

  const handleClick = (e: MouseEvent<HTMLElement>, name: string) => {
    const phase = e.eventPhase === 1 ? "Capture" : "Bubble";
    const color = getColor(name);
    setLog((prevLog) => [...prevLog, { name, phase, color }]);
    console.log(`${name}: ${phase}`);
  };

  const handleDivClick = (e: MouseEvent<HTMLDivElement>) => {
    e.stopPropagation();
    handleClick(e, "INNER");
  };

  const clearLog = () => {
    setLog([]);
  };

畫面結構

  return (
    <div className="p-4 max-w-md mx-auto">
      <div
        className="border-4 border-yellow-500 p-4"
        onClick={(e) => handleClick(e, "OUTER")}
        onClickCapture={(e) => handleClick(e, "OUTER")}
      >
        <div
          className="border-4 border-blue-500 p-4"
          onClick={(e) => handleClick(e, "MIDDLE")}
          onClickCapture={(e) => handleClick(e, "MIDDLE")}
        >
          <div
            className="border-4 border-green-500 p-4"
            onClick={handleDivClick}
            onClickCapture={(e) => handleClick(e, "INNER")}
          >
            <button
              type="button"
              className="bg-red-500 text-white px-4 py-2 rounded"
              onClick={(e) => handleClick(e, "BUTTON")}
              onClickCapture={(e) => handleClick(e, "BUTTON")}
            >
              Click me!
            </button>
          </div>
        </div>
      </div>

      <div className="mt-4">
        <h3 className="font-bold">Event Log:</h3>
        <ul className="list-none pl-0">
          {log.map((entry) => (
            <li key={entry.name} className={`${entry.color} font-semibold`}>
              {entry.name}: {entry.phase}
            </li>
          ))}
        </ul>

        <button
          type="button"
          className="mt-2 bg-gray-500 text-white px-4 py-2 rounded"
          onClick={clearLog}
        >
          Clear Log
        </button>
      </div>
    </div>
  );

DEMO

https://codesandbox.io/p/devbox/6prhn3


上一篇
[Day24]_Sticky-Nav
下一篇
[Day26]_Stripe-Follow-Along-Nav
系列文
React30——用 React 探索 JavaScript30 的魅力30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言