或
我的目标是有条件地向html元素添加id。在JSX中,我遇到了这样的难题:有条件地向html元素添加id:
<SomeHTMLElement id={condition ? "someId" : ""} />
或
<SomeHTMLElement id={condition ? "someId" : null} />
哪种方法是更好的HTML实践?默认是null
还是""
?
如果有另一种方法可以有条件地将id添加到HTML元素中,而不需要向元素本身引入id属性,那也是很好的方法。例如,<HTMLElement id />
或<HTMLElement id="" />
或<HTMLElement id={null} />
最好不要有空的id
属性,这样它就会编译成<HTMLElement />
发布于 2019-06-02 17:00:46
空的ID属性是不好的做法,因为它们是无效的HTML。如果在DOM中不需要ID属性,那么根本不需要输出它。
下面的文档包含一个没有值的id
属性和一个显式空字符串的id=""
属性。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Empty ID validation test</title>
<meta charset="utf-8">
</head>
<body>
<h1>Empty ID validation test</h1>
<p id>This paragraph has an id attribute without a value.</p>
<p id="">This paragraph has an id attribute explicitly set to an empty string.</p>
</body>
</html>
W3C验证器对此给出了两种不同的错误。
p
上的属性id
的值不正确: ID不能为空字符串。”对于此example.id
属性,验证器都会显示此错误。ID必须是唯一的,但是验证器认为id
和id=""
具有相同的值。请注意,尽管在实践this doesn't cause accessibility harm unless the ID is being referred to by an IDREF elsewhere中,重复的in也是WCAG在A级的显式失败(请参阅F77: Failure of Success Criterion 4.1.1 due to duplicate values of type ID)。
在JSX中,我相信将属性设置为null
值(例如<HTMLElement id={null} />
)是防止它出现在DOM中的一种简单方法。注意,我在这里谈论的是实际的DOM,而不是虚拟的DOM。
https://stackoverflow.com/questions/56366659
复制