You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AG-Grid React复选框列无障碍问题求助:重复aria-label报错

解决AG-Grid复选框列重复aria-label导致的无障碍访问错误

问题背景

使用ARC Toolkit检测React应用时,发现26条「重复标签使用」错误,原因是AG-Grid每行的复选框被自动添加了相同的aria-label="Press Space to toggle all rows selection (unchecked)",违反了无障碍访问中元素标签需唯一的要求。

解决方案

核心思路是为每行的复选框生成包含唯一行标识的动态aria-label,以下是两种场景的具体实现:

场景1:自定义复选框列(绑定行数据的selected字段)

写一个自定义单元格渲染器,根据行数据的唯一ID或索引生成专属aria-label:

import React from 'react';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';

const CustomCheckboxRenderer = (props) => {
  // 取行数据的唯一标识(优先用业务ID,无则用行索引)
  const uniqueRowKey = props.data?.id ?? props.rowIndex;
  // 根据当前选中状态动态生成标签文本
  const selectionState = props.value ? 'checked' : 'unchecked';
  const ariaLabel = `Press Space to toggle row ${uniqueRowKey} selection (${selectionState})`;

  return (
    <input
      type="checkbox"
      checked={props.value}
      onChange={(e) => props.setValue(e.target.checked)}
      aria-label={ariaLabel}
    />
  );
};

// 列配置中使用自定义渲染器
const columnDefs = [
  {
    headerName: '选择',
    field: 'selected',
    cellRenderer: CustomCheckboxRenderer,
    editable: true,
    width: 80
  },
  // 其他业务列配置...
];

// 表格组件示例
const MyDataGrid = () => {
  const rowData = [
    { id: 1, name: '张三', selected: false },
    { id: 2, name: '李四', selected: true },
    // 更多行数据...
  ];

  return (
    <div className="ag-theme-alpine" style={{ height: 500, width: '100%' }}>
      <AgGridReact
        columnDefs={columnDefs}
        rowData={rowData}
        rowSelection="multiple"
      />
    </div>
  );
};

export default MyDataGrid;

场景2:使用AG-Grid自带的复选框选择列(checkboxSelection: true)

如果是用AG-Grid原生的选择列配置,通过cellRendererParams动态生成aria-label:

const columnDefs = [
  {
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    width: 80,
    // 动态传入渲染器参数
    getCellRendererParams: (params) => {
      const uniqueRowKey = params.data?.id ?? params.rowIndex;
      // 判断当前行是否被选中
      const isRowSelected = params.api.getSelectedNodes().some(node => node.data.id === uniqueRowKey);
      const selectionState = isRowSelected ? 'checked' : 'unchecked';
      
      return {
        checkboxAriaLabel: `Press Space to toggle row ${uniqueRowKey} selection (${selectionState})`
      };
    }
  },
  // 其他业务列...
];

验证修复

修改完成后,重新用ARC Toolkit扫描应用,确认「重复标签使用」错误全部消除。同时建议用屏幕阅读器测试,确保每个复选框的标签能清晰传达对应的行选择状态。

内容的提问来源于stack exchange,提问作者Ankit Katheriya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:18:21