使用 roving tabindex 实现列表单选键盘导航

解读

国内中高级前端面试常把「无障碍 + 键盘交互」作为区分“只会写页面”与“能交付生产级组件”的试金石。
roving tabindex 是 WAI-ARIA 官方推荐的模式:在列表(listbox、menu、toolbar 等)中只保留一个可聚焦元素,其余元素设置 tabindex="-1",通过 ↑↓ 方向键把焦点“漫游”到当前选项,同时保持 Tab 键在组件层面整体进出。
面试官想考察:

  1. 对无障碍语义与键盘规范是否熟(WCAG、ARIA Authoring Practices)。
  2. 能否用 React 声明式思维管理“谁当前可聚焦”,而不是直接操作 DOM。
  3. 对合成事件、Hook 闭包、可复用性、TypeScript 类型安全是否有落地经验。
  4. 是否了解 Fiber 时间切片与浏览器事件循环,避免在 keydown 里做重计算导致掉帧。

知识点

  • roving tabindex 设计原则:单焦点、方向键漫游、Tab 整体进出。
  • React 合成事件与原生事件差异,event.preventDefault() 与 stopPropagation 的选用。
  • useRef 保存“上一次焦点索引”与“项目长度”,避免重复渲染。
  • useLayoutEffect vs useEffect:测量 DOM 后同步调整焦点,防止闪烁。
  • 受控模式:父组件通过 selectedId 决定当前选项,子组件只报 onSelect。
  • 无障碍语义:role="listbox"、aria-activedescendant、aria-selected、aria-setsize、aria-posinset。
  • 性能:使用 React.memo + 自定义 comparator 防止列表项在漫游时全体 re-render。
  • 兼容性:Safari 下 Option+Tab 会跳过负 tabindex,需要额外提示。
  • 测试:@testing-library/user-event 的 keyboard 方法模拟真实按键,jest-axe 扫描无 ARIA 违规。

答案

以下示例用 TypeScript + Hook 实现一个受控单选列表,支持 ↑↓ 漫游、Home/End 跳转、Tab 整体进出,并附带完整 ARIA 语义。可直接在 CodeSandbox 跑通,也可在面试官电脑现场手写。

// RovingList.tsx
import React, {
  useRef,
  useLayoutEffect,
  KeyboardEvent,
  ReactNode,
  memo,
} from 'react';

export interface Option {
  id: string;
  label: ReactNode;
}

interface Props {
  options: Option[];
  selectedId: string | null;
  onSelect: (id: string) => void;
  ariaLabel?: string;
}

const InnerItem = memo<{ opt: Option; selected: boolean; active: boolean }>(
  ({ opt, selected, active }) => (
    <li
      id={opt.id}
      role="option"
      aria-selected={selected}
      className={`item ${selected ? 'selected' : ''} ${active ? 'active' : ''}`}
    >
      {opt.label}
    </li>
  ),
  (p, n) =>
    p.opt.id === n.opt.id &&
    p.selected === n.selected &&
    p.active === n.active
);

export default function RovingList({
  options,
  selectedId,
  onSelect,
  ariaLabel = '请选择一项',
}: Props) {
  const listRef = useRef<HTMLUListElement>(null);
  const activeIndexRef = useRef<number>(() => {
    const idx = options.findIndex(o => o.id === selectedId);
    return idx >= 0 ? idx : 0;
  });

  // 让 active 项始终保持 tabindex=0,其余为 -1
  useLayoutEffect(() => {
    if (!listRef.current) return;
    const items = Array.from(listRef.current.children) as HTMLLIElement[];
    items.forEach((node, i) => {
      node.tabIndex = i === activeIndexRef.current ? 0 : -1;
      // 同步 aria-activedescendant
      if (i === activeIndexRef.current) {
        listRef.current!.setAttribute('aria-activedescendant', node.id);
      }
    });
    // 焦点若已在组件内,立即迁移
    if (listRef.current.contains(document.activeElement)) {
      items[activeIndexRef.current]?.focus();
    }
  }, [options.length, activeIndexRef.current]);

  const handleKeyDown = (e: KeyboardEvent<HTMLUListElement>) => {
    const max = options.length - 1;
    let next = activeIndexRef.current;

    switch (e.key) {
      case 'ArrowDown':
        next = Math.min(max, activeIndexRef.current + 1);
        break;
      case 'ArrowUp':
        next = Math.max(0, activeIndexRef.current - 1);
        break;
      case 'Home':
        next = 0;
        break;
      case 'End':
        next = max;
        break;
      case 'Enter':
      case ' ':
        onSelect(options[activeIndexRef.current].id);
        return;
      default:
        return;
    }
    e.preventDefault();
    if (next !== activeIndexRef.current) {
      activeIndexRef.current = next;
      // 触发重新渲染,让 useLayoutEffect 调整 tabindex 与焦点
      forceUpdate();
    }
  };

  // 极简 forceUpdate
  const [, forceUpdate] = React.useReducer(x => x + 1, 0);

  return (
    <ul
      ref={listRef}
      role="listbox"
      aria-label={ariaLabel}
      tabIndex={0}
      onKeyDown={handleKeyDown}
      style={{ outline: 'none', padding: 0, margin: 0, listStyle: 'none' }}
    >
      {options.map((opt, i) => (
        <InnerItem
          key={opt.id}
          opt={opt}
          selected={opt.id === selectedId}
          active={i === activeIndexRef.current}
        />
      ))}
    </ul>
  );
}

使用示例:

import React, { useState } from 'react';
import RovingList from './RovingList';

const data = [
  { id: 'beijing', label: '北京' },
  { id: 'shanghai', label: '上海' },
  { id: 'guangzhou', label: '广州' },
  { id: 'shenzhen', label: '深圳' },
];

export default function CitySelector() {
  const [selected, setSelected] = useState<string | null>(null);
  return (
    <div>
      <p>当前选中:{selected ?? '无'}</p>
      <RovingList
        options={data}
        selectedId={selected}
        onSelect={setSelected}
      />
    </div>
  );
}

关键点讲解(面试时口述):

  1. 只保留一个 tabindex=0,其余 -1,让 Tab 键在组件层面整体进出,符合 WCAG 2.1 2.4.3。
  2. 用 useRef 保存活跃索引,避免每次按键都 setState 导致整列表重渲染;真正需要同步 DOM 时再用 forceUpdate 触发 useLayoutEffect,兼顾性能与正确性。
  3. 通过 aria-activedescendant 把虚拟焦点状态通报给读屏软件,确保视力障碍用户感知当前选项。
  4. 把列表项抽成 React.memo,并用自定义 comparator 保证只有“选中”与“活跃”变化才重渲染,60 fps 不卡顿。
  5. 支持空格/回车确认选择,与原生 <select> 行为一致,降低用户学习成本。

拓展思考

  1. 多选场景:在 roving tabindex 基础上增加 aria-multiselectable="true",Shift+↑↓ 连续选择,Ctrl+Space 离散选择,状态机改用 Set<string> 存储已选项。
  2. 动态数据:当列表异步加载或过滤时,需要在 useLayoutEffect 里校正 activeIndexRef,避免越界;同时把焦点安全回退到第一项。
  3. 虚拟滚动:大数据列表(>1000 项)结合 react-window,只在可视区域渲染节点,此时需要用 aria-rowcount/aria-rowindex 补全位置语义,并缓存节点引用以支持漫游。
  4. 移动端:软键盘无 Tab 键,roving tabindex 仍然有效,但需把方向键映射到屏幕上的“上/下”按钮,或监听触摸滑动事件,同步更新 activeIndexRef。
  5. 自动化测试:用 @testing-library/user-event.tab() 验证 Tab 进出,用 keyboard('{ArrowDown>3}') 验证漫游,再用 jest-axe 扫描确保无 aria-activedescendant 指向不存在的 ID。