Skip to content
← Back to rules

jsx-a11y/img-redundant-alt 正确性

它的作用

强制要求 imgalt 属性不包含冗余词汇,例如 "image"、"picture" 或 "photo"。

为什么这是错误的?

屏幕阅读器已经会将 img 元素宣告为图像,因此在 alt 文本中使用 "image"、"photo" 或 "picture" 等词汇是多余的。这会导致辅助技术用户接收到重复信息,使 alt 文本变得不够简洁和有用。

示例

此规则的错误代码示例:

jsx
<img src="foo" alt="Photo of foo being weird." />
<img src="bar" alt="Image of me at a bar!" />
<img src="baz" alt="Picture of baz fixing a bug." />

此规则的正确代码示例:

jsx
<img src="foo" alt="Foo eating a sandwich." />
<img src="bar" aria-hidden alt="Picture of me taking a photo of an image" /> // 将通过,因为该元素被隐藏。
<img src="baz" alt={`Baz taking a ${photo}`} /> // 有效,因为 `photo` 是变量名。

配置

此规则接受一个配置对象,包含以下属性:

components

type: string[]

default: ["img"]

需要验证(组件名称)的 JSX 元素类型,规则适用于这些元素。例如:["img", "Image"]

words

type: string[]

default: ["image", "photo", "picture"]

alt 文本中被视为冗余、应触发警告的词汇。

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "plugins": ["jsx-a11y"],
  "rules": {
    "jsx-a11y/img-redundant-alt": "error"
  }
}
bash
oxlint --deny jsx-a11y/img-redundant-alt --jsx-a11y-plugin

参考资料