如何在React / JSX中指定一个空的alt属性?

war*_*anp 3 javascript accessibility jsx reactjs

我正在尝试向像这样的react组件中的img元素添加一个空的alt属性

function SomeImageComponent(props) { 
  return <img src={props.imgSrc} alt="" />;
}
Run Code Online (Sandbox Code Playgroud)

但是,当将其呈现给DOM并在开发工具中对其进行检查时,我看到这样的布尔类型的属性

<img src="/path/to/cat.gif" alt />
Run Code Online (Sandbox Code Playgroud)

然后,当我使用VoiceOver进行测试时,它会忽略无价值的alt属性,并读出图像的路径。那么我该如何反应为属性值呈现一个空字符串呢?

T.J*_*der 5

alt and alt="" are the same thing. From the spec:

Attributes can be specified in four different ways:

Empty attribute syntax

Just the attribute name. The value is implicitly the empty string.

...

It's true that you typically see this with boolean attributes, but it's not limited to them.

Example:

var imgs = document.querySelectorAll("img");
var alt0 = imgs[0].getAttribute("alt");
var alt1 = imgs[1].getAttribute("alt");
console.log("0 (" + typeof alt0 + "): '" + alt0 + "'");
console.log("1 (" + typeof alt1 + "): '" + alt1 + "'");
Run Code Online (Sandbox Code Playgroud)
<img src="foo.png" alt>
<img src="bar.png" alt="">
Run Code Online (Sandbox Code Playgroud)

It's worth noting that there are only a very few places where a blank alt is appropriate, but if you're supplying it at all, you're probably someone who's already aware of those places. :-)