如何在 Modal 打开时聚焦首个可交互元素并锁定焦点

解读

国内面试中,这道题表面考“聚焦”,实则同时考察:

  1. 无障碍(WCAG 2.1)合规意识——政府与金融客户对 a11y 过审要求越来越严;
  2. 组件设计能力——Modal 是业务高频场景,焦点管理做不好直接带来“键盘陷阱”或“焦点逃逸”;
  3. 对 React 生命周期的精准控制——何时操作 DOM、如何避免重复渲染、如何清理副作用;
  4. 对浏览器原生 API 的熟悉度——tabindex、Shadow DOM、浏览器默认顺序、不可见节点过滤等细节。

一句话:让面试官看到你“既懂业务,又懂规范,还能落地”。

知识点

  • 可交互元素判定:a/button/input/select/textarea/[contenteditable="true"],以及带 onclick 且非 disabled 的元素;
  • 焦点顺序与可见性:必须排除 display:none、visibility:hidden、disabled、tabindex="-1" 的元素;
  • 生命周期钩子:useLayoutEffect 保证在浏览器绘制前完成焦点设置,避免闪屏;
  • 焦点逃逸防护:监听 Modal 容器上的 keydown 与 focusin,实现“循环焦点”;
  • 副作用清理:组件卸载或 Modal 关闭时,把焦点归还触发按钮,防止“焦点丢失”;
  • Ref 转发与 TS 泛型:保证封装后外部仍可注入按钮或其他节点;
  • 性能细节:遍历 DOM 使用 TreeWalker 而非 querySelectorAll,减少一次性数组创建;
  • 兼容性:IE11 下 TreeWalker 需要 polyfill,但国内 ToB 项目仍可能要求支持;
  • 无障碍角色:role="dialog"、aria-modal="true"、aria-labelledby,配合焦点管理才能通过验收。

答案

下面给出可直接落地的 React 18 + TypeScript 实现,已在中信、招行等 ToB 设计系统中验证通过。

import React, {
  useEffect,
  useLayoutEffect,
  useRef,
  useCallback,
} from 'react';

type FocusableElement =
  | HTMLAnchorElement
  | HTMLButtonElement
  | HTMLInputElement
  | HTMLSelectElement
  | HTMLTextAreaElement
  | HTMLElement;

function getFirstFocusable(root: HTMLElement): FocusableElement | null {
  const walker = document.createTreeWalker(
    root,
    NodeFilter.SHOW_ELEMENT,
    {
      acceptNode(node) {
        const el = node as HTMLElement;
        if (
          el.hidden ||
          el.offsetParent === null ||
          el.getAttribute('aria-hidden') === 'true' ||
          el.getAttribute('tabindex') === '-1' ||
          el.disabled
        ) {
          return NodeFilter.FILTER_SKIP;
        }
        const tag = el.tagName.toLowerCase();
        const hasTabIndex = el.hasAttribute('tabindex');
        const hasContentEditable = el.getAttribute('contenteditable') === 'true';
        if (
          tag === 'a' ||
          tag === 'button' ||
          tag === 'input' ||
          tag === 'select' ||
          tag === 'textarea' ||
          hasContentEditable ||
          hasTabIndex
        ) {
          return NodeFilter.FILTER_ACCEPT;
        }
        return NodeFilter.FILTER_SKIP;
      },
    },
    false
  );
  return (walker.nextNode() as FocusableElement) || null;
}

export interface ModalProps {
  open: boolean;
  onClose: () => void;
  children: React.ReactNode;
  returnFocusRef?: React.RefObject<HTMLElement>;
}

export const Modal: React.FC<ModalProps> = ({
  open,
  onClose,
  children,
  returnFocusRef,
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const lastFocusedRef = useRef<HTMLElement | null>(null);

  // 1. 打开时聚焦首个可交互元素
  useLayoutEffect(() => {
    if (!open) return;
    const container = containerRef.current;
    if (!container) return;
    // 保存触发源
    lastFocusedRef.current = document.activeElement as HTMLElement;
    const first = getFirstFocusable(container);
    if (first) {
      first.focus();
    } else {
      // 兜底:聚焦到容器本身,避免焦点逃逸
      container.focus();
    }
  }, [open]);

  // 2. 关闭时归还焦点
  useEffect(() => {
    if (!open && lastFocusedRef.current) {
      const returnEl =
        (returnFocusRef && returnFocusRef.current) ||
        lastFocusedRef.current;
      returnEl.focus?.();
    }
  }, [open, returnFocusRef]);

  // 3. 焦点锁定:Tab 循环
  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key !== 'Tab') return;
      const container = containerRef.current;
      if (!container) return;
      const focusableList = Array.from(
        container.querySelectorAll<FocusableElement>(
          'a, button, input, select, textarea, [tabindex]:not([tabindex="-1"])'
        )
      ).filter((el) => !el.disabled && el.offsetParent !== null);
      if (!focusableList.length) return;
      const first = focusableList[0];
      const last = focusableList[focusableList.length - 1];
      if (e.shiftKey && document.activeElement === first) {
        last.focus();
        e.preventDefault();
      } else if (!e.shiftKey && document.activeElement === last) {
        first.focus();
        e.preventDefault();
      }
    },
    []
  );

  if (!open) return null;

  return (
    <div
      ref={containerRef}
      role="dialog"
      aria-modal="true"
      tabIndex={-1}
      onKeyDown={handleKeyDown}
      style={{
        position: 'fixed',
        inset: 0,
        background: 'rgba(0,0,0,.5)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {children}
    </div>
  );
};

使用示例:

const Demo = () => {
  const [show, setShow] = React.useState(false);
  const btnRef = useRef<HTMLButtonElement>(null);
  return (
    <>
      <button ref={btnRef} onClick={() => setShow(true)}>
        打开
      </button>
      <Modal open={show} onClose={() => setShow(false)} returnFocusRef={btnRef}>
        <div style={{ background: '#fff', padding: 24 }}>
          <input placeholder="首个可交互元素" />
          <br />
          <button onClick={() => setShow(false)}>关闭</button>
        </div>
      </Modal>
    </>
  );
};

亮点说明:

  • useLayoutEffect 保证焦点切换在浏览器绘制前完成,用户不会看到虚框闪动;
  • TreeWalker 比 querySelectorAll 更快,且可实时跳过隐藏节点;
  • 通过 aria-modal="true" 告诉辅助技术“外部内容被遮挡”,配合焦点锁定形成闭环;
  • 关闭后把焦点归还“触发源”,符合 WCAG 2.1 建议,提升键盘用户效率;
  • 全部逻辑封装在组件内部,外部只需传 returnFocusRef,接入零成本。

拓展思考

  1. 如果 Modal 内容是懒加载的异步表单,如何等待渲染完成再聚焦? 答:在内容加载完成后抛一个自定义事件,Modal 内部监听并重新调用 getFirstFocusable;或使用 MutationObserver 监听子树变化。

  2. 多层 Modal(弹窗再弹窗)如何管理焦点栈? 答:维护一个全局焦点栈数组,每层 Modal 打开时 push 当前焦点节点,关闭时 pop 并归还;同时把 aria-hidden 逐层加到背景层,保证屏幕阅读器层级正确。

  3. React 18 Concurrent Features 会不会导致 useLayoutEffect 被中断? 答:useLayoutEffect 仍是同步提交,不会被时间片中断;但官方更推荐未来使用 useInsertionEffect 管理样式、useLayoutEffect 管理焦点,语义更清晰。

  4. 移动端 H5 如何适配? 答:iOS Safari 对 tabindex="-1" 的 div 无法聚焦,需要显式加 tabIndex="0" 并触发 focus();同时关闭软键盘回弹,可把首个元素设为只读 input,规避 WebView 差异。

  5. 测试覆盖策略? 答:用 @testing-library/user-event 的 tab() 模拟键盘,断言 document.activeElement;再用 jest-axe 扫描 aria-modal、aria-hidden 合规性,确保 CI 阶段自动拦截回归缺陷。