标签的EsLint规则

时间:2019-01-30 17:52:48

标签: javascript reactjs

我有问题

My image

我的esLint规则:

"jsx-a11y/label-has-for": [ 2, {
      "components": [],
      "required": {
        "every": [ "nesting", "id" ]
      },
      "allowChildren": true
    }],

我只是想解决这个错误,或者解决问题,请帮帮我

错误消息:表单标签必须与控件关联。 (jsx-a11y / label-has-associated-control)

JSX代码:

          <input
                type="checkbox"
                id="checkbox-2"
                className="checkbox__input"
            />
            <label
                htmlFor="checkbox-2"
                className="checkbox__label"
            />

4 个答案:

答案 0 :(得分:5)

情况1:您可以在标签内输入

  <label>
      <input type="text"/>
  </label>

情况2:使用htmlFor

   <label htmlFor="first-name">
        First Name
   </label>
   <input type="text" id="first-name" />

you can go through the details of rules through this page:

答案 1 :(得分:0)

如果您只想取消此警告,则可以在带有标签的行之前添加特殊注释:

<input type="text" id="myinput" />
<>{ /* eslint-disable-next-line jsx-a11y/label-has-associated-control */ }</>
<label htmlFor="myinput"></label>

在这里您可以找到许多其他用于禁用规则的ESLint内联注释:https://eslint.org/docs/user-guide/configuring#disabling-rules-with-inline-comments

答案 2 :(得分:0)

我通过在eslint文件中添加以下几行来解决了该问题

{
    ....
    "rules": {
      "jsx-a11y/label-has-associated-control": ["error", {
        "required": {
          "some": ["nesting", "id"]
        }
      }],
      "jsx-a11y/label-has-for": ["error", {
        "required": {
          "some": ["nesting", "id"]
        }
      }]
    },
    ...
}

don't forget to restart your local server添加这些行之后。

仅当label htmlFor(React) or for(HTML)input id匹配时有效。

<label htmlFor="temp-id">Label</label>
<input type="text" id="temp-id" />

https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/issues/302#issuecomment-425512505

答案 3 :(得分:-1)

首先,对于这个规则,我需要这样写:"jsx-a11y/label-has-associated-control": "off",

然后我需要关闭此功能:"jsx-a11y/label-has-for":"off",

毕竟,我需要将其移动到文件的顶部,因为就我而言,如果我不将其移动到文件的顶部,则我的规则无效。