简体   繁体   English

在React中使用htmlFor传递eslint html-has-for

[英]Pass eslint html-has-for with htmlFor in React

I have a stateless React component that looks like this: 我有一个无状态的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;

I am using eslint extended with the airbnb config. 我正在使用与airbnb配置扩展的eslint。 My eslint looks like this: 我的eslint看起来像这样:

{
  "extends": "airbnb"
}

My React code throws this error: 我的React代码抛出此错误:

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

I have clearly set an htmlFor attribute with a valid unique id string (which matches the id on an input elsewhere). 我已经清楚地设置了一个带有有效唯一id字符串的htmlFor属性(它与其他地方的输入上的id匹配)。 Surely this is enough to pass this rule? 当然,这足以通过这条规则?

In addition to setting an htmlFor attribute and an id the input element has to be nested inside the label. 除了设置htmlFor属性和id ,input元素必须嵌套在标签内。 You can, however, turn off the nesting requirement if you want. 但是,如果需要,您可以关闭嵌套要求。 Something like this: 像这样的东西:

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

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

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

Eslint doesn't know about the input element that's being rendered elsewhere in your code. Eslint不知道在代码中的其他地方呈现的输入元素。 The error you're getting isn't complaining about the htmlFor attribute per se, it's complaining that as far as it can tell, your htmlFor doesn't refer to a form control element (ie- your input). 你得到的错误并不是抱怨htmlFor属性本身,它抱怨说,就你htmlFor ,你的htmlFor没有引用表单控件元素(即你的输入)。

Try rendering the input alongside your label in the same component, this error should go away. 尝试在同一组件中将标签与标签一起渲染,此错误应该消失。

It seems like you've used it separately from your <input/> tag. 看起来你已经在<input/>标签中单独使用了它。 According to source docs you should put the <input/> inside the <label/> . 根据源文档,您应该将<input/>放在<label/> Or you can set your .eslintrc like this 或者您可以像这样设置.eslintrc

"rules": {
    "jsx-a11y/label-has-for": 0
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM