jsx-a11y/label-has-associated-control Correctness
作用
强制要求 label 标签具有文本标签和关联的控件。
为什么这不好?
表单标签如果没有正确关联到表单控件(例如 <input>),或者不包含可访问文本,就会妨碍使用屏幕阅读器等辅助技术的用户进行访问。用户可能没有足够的信息来理解表单控件的用途。
示例
以下是此规则的错误代码示例:
jsx
function Foo(props) {
return <label {...props} />
}
<input type="text" />
<label>Surname</label>以下是此规则的正确代码示例:
jsx
function Foo(props) {
const { htmlFor, ...otherProps } = props;
return <label htmlFor={htmlFor} {...otherProps} />;
}
<label>
<input type="text" />
姓氏
</label>;配置
此规则接受一个具有以下属性的配置对象:
assert
type: "htmlFor" | "nesting" | "both" | "either"
default: "either"
label 与控件之间所需的关联类型。
"htmlFor"
断言 label 使用 htmlFor 来关联一个控件。
"nesting"
断言 label 包含一个嵌套的控件
"both"
断言 label 同时使用 htmlFor 和嵌套来关联一个控件
"either"
断言 label 使用 htmlFor 或嵌套中的任一种来关联一个控件
controlComponents
type: string[]
default: []
将被视为表单控件的自定义 JSX 组件。
depth
type: integer
default: 2
搜索嵌套控件的最大深度。
labelAttributes
type: string[]
default: ["alt", "aria-label", "aria-labelledby"]
用于检查可访问标签文本的属性。
labelComponents
type: string[]
default: ["label"]
将被视为标签的自定义 JSX 组件。
如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["jsx-a11y"],
"rules": {
"jsx-a11y/label-has-associated-control": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["jsx-a11y"],
rules: {
"jsx-a11y/label-has-associated-control": "error",
},
});bash
oxlint --deny jsx-a11y/label-has-associated-control --jsx-a11y-plugin版本
此规则在 v0.9.1 中新增。
