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

如何让WebHint将React-Intl <FormattedMessage>识别为<button>的有效标签?

解决WebHint对FormattedMessage作为按钮文本的误报问题

WebHint的axe/name-role-value规则误报是因为静态检查无法识别<FormattedMessage>动态渲染的文本,以下几种方法可以解决:

  • 使用aria-labelledby关联文本元素
    给<FormattedMessage>添加唯一id,让按钮通过aria-labelledby引用这个id,明确告知辅助工具按钮的文本来源:

    function MyButton({ labelId, onClick }) {
      const messageId = `button-message-${labelId}`;
      return (
        <button type="button" onClick={onClick} aria-labelledby={messageId}>
          <FormattedMessage id={labelId} data-testid={messageId} />
        </button>
      );
    }
    
  • 直接设置aria-label属性
    通过react-intl的useIntl钩子获取格式化后的文本,直接给按钮设置aria-label:

    import { useIntl } from 'react-intl';
    
    function MyButton({ labelId, onClick }) {
      const intl = useIntl();
      const buttonLabel = intl.formatMessage({ id: labelId });
      
      return (
        <button type="button" onClick={onClick} aria-label={buttonLabel}>
          <FormattedMessage id={labelId} />
        </button>
      );
    }
    
  • 调整WebHint规则配置
    在项目的.hintrc文件中,修改axe/name-role-value规则的配置,忽略按钮子元素为<FormattedMessage>的情况:

    {
      "extends": ["development"],
      "rules": {
        "axe/name-role-value": {
          "options": {
            "rules": {
              "name-role-value": {
                "enabled": true,
                "selector": ":not(button:has(> FormattedMessage))"
              }
            }
          }
        }
      }
    }
    

注意:第三种方法需要确保WebHint版本支持自定义选择器过滤,部分旧版本可能不兼容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:47:03