新增工具! 探索最新内容

首页/组件/模态对话框

模态对话框 examples

基于原生 dialog 元素构建的无障碍模态框,带有背景遮罩、焦点锁定和按 Escape 关闭。

基于浏览器原生 dialog 元素构建的模态对话框,因此焦点锁定、背景遮罩渲染和按 Escape 关闭都来自平台,而不是需要你维护的 JavaScript。

包含点击背景关闭、正确的 ARIA 标注,以及一个把 open 属性同步到元素自身方法的 React 封装。

Confirmation modal dialog

Two actions with the destructive one in red and placed last. The button names the action, so it reads correctly on its own.

Preview
"use client";

import { useRef } from "react";

export default function ConfirmDialog() {
  const ref = useRef<HTMLDialogElement>(null);

  return (
    <>
      <button
        type="button"
        onClick={() => ref.current?.showModal()}
        className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
      >
        Delete project
      </button>

      <dialog
        ref={ref}
        onClick={(e) => {
          if (e.target === ref.current) ref.current?.close();
        }}
        aria-labelledby="dialog-title"
        aria-describedby="dialog-description"
        className="m-auto w-full max-w-md rounded-xl p-0 backdrop:bg-gray-900/50"
      >
        <div className="p-6">
          <h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Delete this project?</h2>
          <p id="dialog-description" className="mt-2 text-sm text-gray-600">
            This removes the project and all of its files. This action cannot be undone.
          </p>

          <div className="mt-6 flex justify-end gap-3">
            <button type="button" onClick={() => ref.current?.close()} className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Cancel</button>
            <button type="button" onClick={() => ref.current?.close()} className="rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-500">Delete project</button>
          </div>
        </div>
      </dialog>
    </>
  );
}

Modal dialog with a form

A single-field form using method=dialog, so submitting closes the dialog and reports the clicked button's value without extra wiring.

Preview
"use client";

import { useRef } from "react";

export default function RenameDialog() {
  const ref = useRef<HTMLDialogElement>(null);

  return (
    <>
      <button
        type="button"
        onClick={() => ref.current?.showModal()}
        className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
      >
        Rename project
      </button>

      <dialog
        ref={ref}
        onClick={(e) => {
          if (e.target === ref.current) ref.current?.close();
        }}
        aria-labelledby="dialog-title"
        aria-describedby="dialog-description"
        className="m-auto w-full max-w-md rounded-xl p-0 backdrop:bg-gray-900/50"
      >
        <form method="dialog" className="p-6">
          <h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Rename project</h2>
          <p id="dialog-description" className="mt-2 text-sm text-gray-600">Choose a name your team will recognize.</p>

          <label htmlFor="project-name" className="mt-4 block text-sm font-medium text-gray-900">Project name</label>
          <input id="project-name" name="name" type="text" required autoComplete="off" className="mt-1.5 block w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900" />

          <div className="mt-6 flex justify-end gap-3">
            <button type="button" onClick={() => ref.current?.close()} className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Cancel</button>
            <button type="submit" className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">Save name</button>
          </div>
        </form>
      </dialog>
    </>
  );
}

Bottom sheet modal on mobile

Pinned to the bottom edge with a drag-handle cue below the sm breakpoint, and a centered dialog above it.

Preview
"use client";

import { useRef } from "react";

export default function ShareSheet() {
  const ref = useRef<HTMLDialogElement>(null);

  return (
    <>
      <button
        type="button"
        onClick={() => ref.current?.showModal()}
        className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
      >
        Share
      </button>

      <dialog
        ref={ref}
        onClick={(e) => {
          if (e.target === ref.current) ref.current?.close();
        }}
        aria-labelledby="dialog-title"
        aria-describedby="dialog-description"
        className="m-0 mt-auto w-full max-w-none rounded-b-none rounded-t-2xl p-0 backdrop:bg-gray-900/50 sm:m-auto sm:max-w-md sm:rounded-xl"
      >
        <div className="p-6">
          <div className="mx-auto mb-4 h-1.5 w-10 rounded-full bg-gray-300 sm:hidden" aria-hidden="true"></div>
          <h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Share this page</h2>
          <p id="dialog-description" className="mt-1 text-sm text-gray-600">Anyone with the link can view it.</p>

          <ul className="mt-4 space-y-1">
            <li><button type="button" onClick={() => ref.current?.close()} className="block w-full rounded-md px-3 py-2.5 text-left text-sm text-gray-900 hover:bg-gray-100">Copy link</button></li>
            <li><button type="button" onClick={() => ref.current?.close()} className="block w-full rounded-md px-3 py-2.5 text-left text-sm text-gray-900 hover:bg-gray-100">Send by email</button></li>
            <li><button type="button" onClick={() => ref.current?.close()} className="block w-full rounded-md px-3 py-2.5 text-left text-sm text-gray-900 hover:bg-gray-100">Open in a new tab</button></li>
          </ul>

          <button type="button" onClick={() => ref.current?.close()} className="mt-4 w-full rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Cancel</button>
        </div>
      </dialog>
    </>
  );
}

Side drawer modal

A full-height panel on the right for filters or settings. Still a native modal dialog, so focus trapping and Escape work the same way.

Preview
"use client";

import { useRef } from "react";

export default function FilterDrawer() {
  const ref = useRef<HTMLDialogElement>(null);

  return (
    <>
      <button
        type="button"
        onClick={() => ref.current?.showModal()}
        className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
      >
        Open filters
      </button>

      <dialog
        ref={ref}
        onClick={(e) => {
          if (e.target === ref.current) ref.current?.close();
        }}
        aria-labelledby="dialog-title"
        className="m-0 ml-auto h-screen max-h-none w-full max-w-sm rounded-none p-0 backdrop:bg-gray-900/50"
      >
        <div className="flex h-full flex-col">
          <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
            <h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Filters</h2>
            <button type="button" onClick={() => ref.current?.close()} aria-label="Close filters" className="rounded-md p-2 text-gray-500 hover:bg-gray-100">
              <svg className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
            </button>
          </div>

          <div className="flex-1 overflow-y-auto px-6 py-5">
            <fieldset>
              <legend className="text-sm font-medium text-gray-900">Category</legend>
              <div className="mt-3 space-y-2 text-sm text-gray-700">
                <label className="flex items-center gap-2"><input type="checkbox" className="h-4 w-4 rounded border-gray-300" /> Design</label>
                <label className="flex items-center gap-2"><input type="checkbox" className="h-4 w-4 rounded border-gray-300" /> Engineering</label>
                <label className="flex items-center gap-2"><input type="checkbox" className="h-4 w-4 rounded border-gray-300" /> Marketing</label>
              </div>
            </fieldset>
          </div>

          <div className="flex gap-3 border-t border-gray-200 px-6 py-4">
            <button type="button" onClick={() => ref.current?.close()} className="flex-1 rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Clear</button>
            <button type="button" onClick={() => ref.current?.close()} className="flex-1 rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">Show results</button>
          </div>
        </div>
      </dialog>
    </>
  );
}

Scrollable modal with sticky header and footer

Long content scrolls inside the panel while the title and actions stay visible. Uses open:flex so the closed dialog stays hidden.

Preview
"use client";

import { useRef } from "react";

export default function TermsDialog() {
  const ref = useRef<HTMLDialogElement>(null);

  return (
    <>
      <button
        type="button"
        onClick={() => ref.current?.showModal()}
        className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700"
      >
        Review terms
      </button>

      <dialog
        ref={ref}
        onClick={(e) => {
          if (e.target === ref.current) ref.current?.close();
        }}
        aria-labelledby="dialog-title"
        className="m-auto max-h-[80vh] w-full max-w-lg flex-col rounded-xl p-0 backdrop:bg-gray-900/50 open:flex"
      >
        <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
          <h2 id="dialog-title" className="text-lg font-semibold text-gray-900">Terms of service</h2>
          <button type="button" onClick={() => ref.current?.close()} aria-label="Close terms" className="rounded-md p-2 text-gray-500 hover:bg-gray-100">
            <svg className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
          </button>
        </div>

        <div className="min-h-0 flex-1 space-y-3 overflow-y-auto px-6 py-4 text-sm text-gray-600">
          <p>Section 1. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
          <p>Section 2. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
          <p>Section 3. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
          <p>Section 4. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
          <p>Section 5. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
          <p>Section 6. These terms describe how the service may be used, what you can expect from us, and what we expect from you. Read each section before continuing.</p>
        </div>

        <div className="flex justify-end gap-3 border-t border-gray-200 px-6 py-4">
          <button type="button" onClick={() => ref.current?.close()} className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50">Decline</button>
          <button type="button" onClick={() => ref.current?.close()} className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700">Accept</button>
        </div>
      </dialog>
    </>
  );
}

What is a 模态对话框?

模态对话框是在页面之上打开的面板,在处理完之前会阻止与其背后一切内容的交互。阻止正是它的全部意义:它用于那些不做决定就继续是错误的时刻,比如确认删除或完成必需步骤。任何不需要打断用户的内容,都应该改用页面、面板或 Toast。

模态框众所周知很难正确构建,这也是为什么存在这么多相关的库。必须做对的事项清单很长:打开时焦点必须移入对话框,关闭时返回触发元素;Tab 必须在面板内循环而不是逃到背后的页面;背后的页面不能滚动;Escape 必须能关闭它;对话框必须带名称和角色被播报;并且打开时,下面的一切都必须对辅助技术隐藏。

原生 dialog 元素现在几乎处理了所有这些。对它调用 showModal 会锁定焦点、渲染背景伪元素、使文档其余部分惰性化,并把 Escape 连接到关闭--这些行为过去需要几百行精心编写的 JavaScript。自 2022 年起浏览器支持已十分广泛,使得手工构建的版本在新工作中很难自圆其说。

平台没有提供的是点击背景关闭,因为背景是伪元素,而不是可以监听的节点。变通方法是监听 dialog 自身上的点击,并检查点击目标是否是 dialog 本身而不是其内部的内容--直接落在 dialog 元素上的点击来自面板之外的内边距区域,从用户的角度看就是背景。

Anatomy

触发器
打开对话框的按钮。关闭时焦点会自动返回这里,因此触发器应当是真正的按钮,而不是带处理函数的 div。
dialog 元素
原生 dialog。承载宽度限制和背景样式,内边距设为零,由内部容器控制间距。
背景遮罩
通过 backdrop 伪类设置样式,而不是用单独的元素。它只在通过 showModal 打开对话框时存在。
标题
对话框的无障碍名称,用 aria-labelledby 关联。写成问题或任务,而不是分类标签。
描述
可选的辅助文字,用 aria-describedby 关联。对于破坏性操作,后果应写在这里。
操作行
底部按钮,靠右对齐,主要或破坏性操作放在最后,使其最靠近拇指和视线的终点。

How to Use

  1. 1

    复制标记

    静态页面选用 HTML 版本,组件树选用 React 封装。两者底层使用同一个原生元素。

  2. 2

    用 showModal 打开

    调用 showModal 而不是 show。普通的 show 方法打开对话框时没有背景遮罩,没有焦点锁定,也不会使页面其余部分惰性化。

  3. 3

    接入关闭途径

    Escape 由浏览器处理。添加关闭按钮和背景点击处理函数,这样就有三种退出方式,并让它们都经过同一个 onClose。

  4. 4

    为对话框命名

    让 aria-labelledby 指向标题的 id,如果有描述,则让 aria-describedby 指向描述。没有名称时,对话框会被播报为未命名的对话框。

  5. 5

    设计面板样式

    把内边距设在内部容器而不是 dialog 本身上,使背景点击检测保持可靠--dialog 上的内边距会成为它自己点击区域的一部分。

Features

原生焦点锁定

焦点在打开时移入对话框并在其中循环,由浏览器处理,而不是需要你始终保持正确的 keydown 监听器。

焦点返回触发器

关闭时,焦点会自动回到打开对话框的元素,因此键盘用户可以从离开的地方继续。

无需额外元素的背景遮罩

背景遮罩是用 backdrop 变体设置样式的伪元素,因此没有需要定位、层叠或保持同步的单独遮罩 div。

按 Escape 关闭

内置于元素中。React 封装会监听由此触发的 close 事件,使浏览器自行关闭对话框时 open 属性仍保持同步。

页面其余部分变为惰性

模态对话框后面的内容无法聚焦,并对辅助技术隐藏,无需手动给任何元素设置 aria-hidden。

点击背景关闭

通过点击目标检查区分内边距区域和面板内容,无需额外的遮罩节点,就能提供人们期望的关闭行为。

Common Uses

确认破坏性操作

删除账户、项目或文件--这类情形下误点会产生无法靠 Toast 撤销的后果。

简短表单

重命名某项、邀请队友或输入单个值,这时把人送到单独页面会让他们失去当前位置。

必需的引导步骤

继续之前确实必须完成的步骤,例如接受更新后的条款或选择工作区。

媒体和详情视图

在当前页面之上显示更大的图片或某条记录的详情,这时返回到相同的滚动位置很重要。

Accessibility

Customization

Props

PropTypeDefaultDescription
open *boolean-对话框是否显示。组件把该值同步到原生的 showModal 和 close 方法,而不是有条件地渲染该元素。
onClose *() => void-当对话框通过任何途径关闭时调用--Escape 键、点击背景或关闭按钮。用它把 open 设回 false。
title *string-对话框的无障碍名称,通过 aria-labelledby 关联。切勿省略;没有名称的对话框只会被播报为“对话框”。
descriptionstring-可选的辅助文字,通过 aria-describedby 关联,使其在标题之后被朗读而不是被跳过。
childrenReactNode-对话框的主体和操作。把操作放在最后,使 Tab 顺序先经过内容再到达操作。

Why Use These 模态对话框s?

它使用平台能力,而不是重新实现它。焦点锁定、惰性背景和 Escape 处理正是手工构建的模态框最容易出错的部分,在这里它们是浏览器的责任,而不是你的。

这也意味着没有依赖。无头对话框库是合理的选择,但对于一个确认提示来说,它意味着要发布一个包、追踪其版本,并学习其 API,才能得到该元素本来就提供的行为。

React 封装同步到元素自身的状态,而不是有条件地渲染它,因此被 Escape 关闭的对话框仍会触发 onClose,open 属性也不会与屏幕上的实际情况脱节。

Tips

Frequently Asked Questions

Related Components