繁体   English   中英

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

[英]Prop in stateless component fat arrow function cannot be validated with 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;

埃斯林特告诉我:

道具验证中缺少“bar”

似乎当粗箭头返回 JSX 时,eslint 失败了。

我可以通过为此分配bar来解决this

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

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

这是最好的方法吗? 为什么会这样?

.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,
  }
}

我想象正在发生的事情是myFunc被视为另一个无状态组件。 只是盯着你的代码,它看起来是有效的,但 eslint 可能认为myFunc需要自己的propTypes ,即使你正在访问的props在同一范围内。 您可以通过执行以下操作来验证这一点:

const myFunc = (props) => (
  <div>
    { props.bar }
  </div>
);
myFunc.propTypes = {
  bar: PropTypes.string.isRequired,
};

return myFunc({ bar: props.bar });

但是对于这方面的实用建议,我建议返回

<div>
  { props.bar }
</div>

从你的Foo而不是在里面创建一个闭包。

如果你这样做会发生什么?

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

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

  // access bar here.
  return myFunc(props.bar);
};

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

export default Foo;

我发现了一个奇怪的行为。 唯一的区别在于 return 语句: 在此处输入图片说明 在此处输入图片说明

现在propTypesbar也没有注释: 在此处输入图片说明 在此处输入图片说明

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

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

此外,这很有趣,如果您只是将props重命名为其他任何内容,eslint 将保持沉默 :)
在此处输入图片说明

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

暂无
暂无

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

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