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

时间:2017-06-19 13:47:07

标签: javascript reactjs accessibility jsx

我试图将空的alt属性添加到反应组件中的img元素,如此

function SomeImageComponent(props) { 
  return <img src={props.imgSrc} alt="" />;
}

但是当它被渲染到DOM并且我在开发工具中检查它时,我看到一个像这样的布尔类型的属性

<img src="/path/to/cat.gif" alt />

当我使用VoiceOver对其进行测试时,它会忽略无值alt属性并读出图像的路径。那么如何才能对属性值呈现空字符串做出反应?

2 个答案:

答案 0 :(得分: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 + "'");
<img src="foo.png" alt>
<img src="bar.png" alt="">

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. :-)

答案 1 :(得分:0)

我们还可以添加alt标签吗? 通过这样做,我们可以克服Google和工具错误通知

<img src="foo.png" alt="foo">
<img src="bar.png" alt="bar">