Frontend Lab
← 回到所有模式
PB01🪟 Overlay · 覆蓋層對話框

Modal

對話框

難度 ★★★★★標籤 modal · 焦點陷阱 · ESC3 min read

模式簡述

Modal:點開後背景變暗、ESC 可關、tab 鍵被困在對話框內、return focus 回觸發按鈕。背景捲動要鎖。

關閉|預設關閉

Claude Code Prompt

💬 Claude Code Prompt
參考:PB01 modal
組件:Modal.tsx

Modal:點開後背景變暗、ESC 可關、tab 鍵被困在對話框內、return focus 回觸發按鈕。背景捲動要鎖。

限制:
- 忘了鎖背景捲動
- 焦點不還回去
- ESC 鍵忘了綁

完整程式碼

Modal.tsx
"use client";
import { useEffect, useState } from "react";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";

type State = "closed" | "open" | "destructive";

export function Modal({ state = "open" }: { state?: State }) {
const [open, setOpen] = useState(state !== "closed");
useEffect(() => setOpen(state !== "closed"), [state]);
const destructive = state === "destructive";

return (
  <div className="relative grid h-[280px] w-full max-w-md place-items-center rounded-lg border border-border bg-background/30">
    <button
      type="button"
      onClick={() => setOpen(true)}
      className="rounded-md border border-border bg-background/50 px-3 py-1.5 font-mono text-xs text-muted-foreground hover:border-lab-accent"
    >
      開啟 modal
    </button>
    {open && (
      <>
        <div
          onClick={() => setOpen(false)}
          className="absolute inset-0 bg-black/60 backdrop-blur-sm animate-in fade-in duration-200"
        />
        <div className="absolute left-1/2 top-1/2 w-[88%] -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-background p-5 shadow-2xl animate-in fade-in zoom-in-95 duration-200">
          <div className="flex items-start justify-between gap-3">
            <h3 className="text-sm font-medium text-foreground">
              {destructive ? "確認刪除?" : "確認你的選擇"}
            </h3>
            <button onClick={() => setOpen(false)} className="text-muted-foreground hover:text-foreground">
              <X className="h-4 w-4" />
            </button>
          </div>
          <p className="mt-2 text-xs text-muted-foreground" style={{ fontFamily: "var(--font-zh)" }}>
            {destructive
              ? "此動作無法復原。確認後資料會永久刪除。"
              : "送出後即可繼續下一步。"}
          </p>
          <div className="mt-4 flex justify-end gap-2">
            <button
              onClick={() => setOpen(false)}
              className="rounded-md border border-border bg-background px-3 py-1.5 text-xs hover:border-lab-accent"
            >
              取消
            </button>
            <button
              className={cn(
                "rounded-md border px-3 py-1.5 text-xs",
                destructive
                  ? "border-red-500 bg-red-500/10 text-red-500 hover:bg-red-500/20"
                  : "border-lab-accent bg-lab-accent/10 text-lab-accent hover:bg-lab-accent/20",
              )}
            >
              {destructive ? "刪除" : "確認"}
            </button>
          </div>
        </div>
      </>
    )}
  </div>
);
}

何時用

  • ✅ 重要決策需要使用者明確回應
  • ✅ 編輯表單但又不想整頁切換
  • ✅ 確認破壞性動作

何時別用

  • ❌ 路徑可以表達的內容(用 route 而不是 modal)
  • ❌ 資訊量超過半個螢幕(改用 page)
  • ❌ 需要多步驟流程(用 stepper 或 wizard)

我踩過的坑

  1. 忘了鎖背景捲動:iOS 上背景會隨手指滑動,使用者搞不清楚誰在動。body 加 overflow-hidden。

  2. 焦點不還回去:關閉後焦點掉回 body,鍵盤使用者要重新 tab。記得存 trigger ref,關閉時 .focus()。

  3. ESC 鍵忘了綁:用 onKeyDown + key === 'Escape',但要綁在 document 不是 element。

相關模式

  • PB02
  • PB11
  • PF04

搜尋

按 ⌘K 隨時開啟