【问题标题】:when image tag role be set button jsx-a11y show warning设置图像标签角色时按钮 jsx-a11y 显示警告
【发布时间】:2018-11-06 06:51:47
【问题描述】:

我需要使图像标签可点击,但我收到 jsx-a11y 的警告,我该如何修复它,我已经阅读了no-noninteractive-element-interactions,但我不想将其他 div 标签包装在 img 标签周围,因为它会使一个冗余标签,还有其他方法可以解决这个警告吗?

警告是[eslint] Non-interactive elements should not be assigned interactive roles.

我的代码是

  <img
    styleName="pic-id-code"
    src={picCodeImgSrc}
    alt="pic id code"
    onClick={this.refreshPicCodeImg}
    onKeyPress={this.handleKeyPress}
    role="button"
    tabIndex="0"
  />

【问题讨论】:

    标签: reactjs eslint


    【解决方案1】:

    您应该将&lt;input type="image" /&gt; 用于您的用例,它在语义上是正确的,您不需要添加roletabindex 或任何其他ARIA 标记来使其工作和访问。

    有一个警告,因为点击后它实际上并没有恢复正常状态并保持焦点,因此您需要在 onClick 逻辑之后调用 blur。这是我几天前创建的simple demo,以消除对点击的关注。

    【讨论】:

    • 一段时间以来,我一直在尝试找出实现这一目标的最佳方法。这无疑是最好、最正确的解决方案!
    【解决方案2】:

    您可以像这样为指定行禁用 eslint

    // eslint-disable-next-line THE-RULE-HERE
    <img
        styleName="pic-id-code"
        src={picCodeImgSrc}
        alt="pic id code"
        onClick={this.refreshPicCodeImg}
        onKeyPress={this.handleKeyPress}
        role="button"
        tabIndex="0"
      />
    

    不确定你的规则到底是什么,但试试这个

    // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
    

    // eslint-disable-next-line no-noninteractive-element-interactions
    

    OP 评论后更新

    ...但是在 react jsx 中没有工作

    试试这个

    <img
            styleName="pic-id-code"
            src={picCodeImgSrc}
            alt="pic id code"
            // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
            onClick={this.refreshPicCodeImg}
            // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
            onKeyPress={this.handleKeyPress}
            // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
            role="button"
            tabIndex="0"
          />
    

    img 上的onClickoneKeyPress 也会触发警告。

    【讨论】:

    • 我尝试了更新的答案,但也有错误,Non-interactive elements should not be assigned interactive roles.
    • 是同一行吗?还需要检查我们使用的规则是否正确。试试通用的,没有任何规则// eslint-disable-next-line
    • 是的,同一行,我使用vscode和eslint插件,所以当得到eslint错误或警告时我可以看到红线突出显示
    • 你在 vscode 中使用哪个扩展来进行 linting?是vscode-eslint吗?如果是,试试这个github.com/Microsoft/vscode-eslint/pull/530
    • 是的,我使用这个插件,我将 vscode 设置更改为 ` "eslint.autoFixOnSave": true,, so if eslint can fix it, it'll auto fix when I save the file, but not, and these disable eslint` 也不起作用
    猜你喜欢
    • 2023-03-24
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2017-09-28
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多