代码之家  ›  专栏  ›  技术社区  ›  CaribouCode

在React中用htmlFor传递eslint html的for

  •  8
  • CaribouCode  · 技术社区  · 7 年前

    我有一个无状态React组件,看起来像这样:

    const propTypes = exact({
      fieldId: PropTypes.string.isRequired,
      text: PropTypes.string.isRequired,
    });
    
    function Label({ fieldId, text }) {
      return (
        <label htmlFor={fieldId}>{text}</label>
      );
    }
    
    Label.propTypes = propTypes;
    

    我正在使用扩展了airbnb配置的eslint。我的eslint看起来像这样:

    {
      "extends": "airbnb"
    }
    

    我的React代码引发以下错误:

    error  Form label must have associated control  jsx-a11y/label-has-for
    

    我已经明确设定了 htmlFor 具有有效唯一id字符串(与其他地方输入的id匹配)的属性。这就足够通过这条规则了吗?

    3 回复  |  直到 7 年前
        1
  •  14
  •   devk    7 年前

    除了设置 htmlFor 属性和an id 输入元素必须嵌套在标签内。 但是,如果需要,可以关闭嵌套要求。类似这样:

    {
      "extends": "airbnb",
      "rules": {
        "jsx-a11y/label-has-for": [ 2, {
          "required": {
              "every": [ "id" ]
          }
      }]
      }
    }
    

    与您的问题相关的问题: https://github.com/evcohen/eslint-plugin-jsx-a11y/issues/314

    文档: https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md

        2
  •  3
  •   Ihor    7 年前

    看起来你已经把它和你的 <input/> 标签根据 source docs 你应该把 <输入/> 内部 <label/> . 或者你可以设置你的。像这样

    "rules": {
        "jsx-a11y/label-has-for": 0
     }
    
        3
  •  2
  •   Donny West    7 年前

    Eslint不知道代码中其他地方呈现的输入元素。你得到的错误不是抱怨 htmlFor 属性本身,它在抱怨,据它所知,你的 htmlFor公司 不引用表单控件元素(即您的输入)。

    尝试在同一组件中与标签一起呈现输入,此错误应该会消失。