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>
);