useUniqueElementIds
¥Summary
-
规则生效日期:
v2.0.0¥Rule available since:
v2.0.0 -
诊断类别:
lint/correctness/useUniqueElementIds¥Diagnostic Category:
lint/correctness/useUniqueElementIds -
此规则没有修复方案。
¥This rule doesn’t have a fix.
-
此规则的默认严重级别为 error。
¥The default severity of this rule is error.
-
此规则属于以下域:
¥This rule belongs to the following domains:
¥How to configure
{ "linter": { "rules": { "correctness": { "useUniqueElementIds": "error" } } }}¥Description
防止在元素上使用静态字符串字面量 id 属性。
¥Prevent the usage of static string literal id attribute on elements.
在 React 中,不建议硬编码 ID,因为 ID 在 DOM 中必须是唯一的。为了提高可访问性,你应该使用 useId 生成唯一 ID。
¥In React, hardcoding IDs is discouraged because IDs have to be unique in the DOM.
You should use useId to generate unique IDs for accessibility purposes.
请注意,此规则不会检查 ID 是否真正唯一,但会检查是否将静态字面 ID 传递给了元素。因此,我们鼓励你自行检查 ID 是否确实唯一。
¥Please keep in mind this rule doesn’t check whether ids are actually unique or not, and does check whether static literal id isn’t passed to the elements or not. So you’re encouraged to check by yourself if the ids are actually unique.
¥Examples
¥Invalid
<div id="foo">bar</div>;code-block.jsx:1:1 lint/correctness/useUniqueElementIds ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ id attribute should not be a static string literal. Generate unique IDs using useId().
> 1 │ <div id=“foo”>bar</div>;
│ ^^^^^^^^^^^^^^
2 │
ℹ In React, if you hardcode IDs and use the component multiple times, it can lead to duplicate IDs in the DOM. Instead, generate unique IDs using useId().
React.createElement("div", { id: "foo" });code-block.jsx:1:1 lint/correctness/useUniqueElementIds ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ id attribute should not be a static string literal. Generate unique IDs using useId().
> 1 │ React.createElement(“div”, { id: “foo” });
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 │
ℹ In React, if you hardcode IDs and use the component multiple times, it can lead to duplicate IDs in the DOM. Instead, generate unique IDs using useId().
¥Valid
const id = useId();<div id={id}>bar</div>;const id = useId();React.createElement("div", { id });¥Options
以下选项可用
¥The following option is available
excludedComponents
Section titled “excludedComponents”要忽略的不合格组件名称列表。使用 id 列出期望具有不代表 DOM 元素 ID 的 id 属性的组件。
¥List of unqualified component names to ignore.
Use it to list components expecting an id attribute that does not represent
a DOM element ID.
默认:空列表。
¥Default: empty list.
{ "linter": { "rules": { "correctness": { "useUniqueElementIds": { "options": { "excludedComponents": [ "FormattedMessage" ] } } } } }}<FormattedMessage id="static" /><Library.FormattedMessage id="static" />¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号