无状态组件胖箭头函数中的 Prop 无法使用 eslint 进行验证

Mis*_*pic 5 reactjs eslint

我有以下内容:

import React from 'react';
import PropTypes from 'prop-types';

const Foo = (props) => {
  const myFunc = () => (
    <div>
      { props.bar }
    </div>
  );

  return myFunc();
};

Foo.propTypes = {
  bar: PropTypes.string.isRequired,
};

export default Foo;
Run Code Online (Sandbox Code Playgroud)

埃斯林特告诉我:

道具验证中缺少“bar”

看起来好像当粗箭头返回 JSX 时,eslint 失败了。

bar我可以通过分配给来解决这个问题this

const Foo = (props) => {
  this.bar = props.bar; //eslint sees this properly

  const myFunc = () => (
    <div>
      { this.bar }
    </div>
  );
Run Code Online (Sandbox Code Playgroud)

这是解决这个问题的最佳方法吗?为什么会发生这种情况?

.eslintrc

// .eslint.json

{
  "extends": "airbnb",
  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaVersion": 2016,
    "sourceType": "module",
    "ecmaFeatures": {
    "jsx": true
    }
  },
  "env": {
    "browser": true,
     "es6": true,
     "jest": true
  },
  "plugins": [
    "react",
    "import",
    "jsx-a11y"
  ],
  "rules": {
        "react/jsx-filename-extension": 0,
        "func-names": 0,
        "strict": 0,
        "quotes": [1, "single"],
        "no-confusing-arrow": 0,
        "react/prefer-es6-class": 0,
        "babel/generator-star-spacing": 0,
        "no-underscore-dangle": 0,
        "linebreak-style": ["error", "windows"],
        "no-named-as-default": 0,
  }
}
Run Code Online (Sandbox Code Playgroud)

Qwe*_*rty 1

我发现了一个奇怪的行为。唯一的区别在于返回语句: 在此输入图像描述 在此输入图像描述

现在barin也propTypes未注释: 在此输入图像描述 在此输入图像描述

PS:您还可以使用解构来绕过 props 验证,Foo = ({ bar }) => ...而不必分配它const bar = props.bar

我认为问题是因为它myFunc看起来像一个功能组件,而 eslint 错误地选择了它。
在此输入图像描述

另外,这很有趣,如果你只是将 重命名props为其他名称,eslint 就会保持沉默:)
在此输入图像描述

//编辑似乎我的推理有些正确https://github.com/yannickcr/eslint-plugin-react/issues/2135#issuecomment-455034857