React eslint 道具验证中缺少错误

问题描述 投票:0回答:16

我有下一个代码,eslint throw:

react/prop-types onClickOut;道具验证中缺失

react/prop-types 子项;道具验证中缺失

propTypes
已定义,但 eslint 无法识别它。

import React, { Component, PropTypes } from 'react';

class IxClickOut extends Component {
  static propTypes = {
    children: PropTypes.any,
    onClickOut: PropTypes.func,
  };

 componentDidMount() {
    document.getElementById('app')
      .addEventListener('click', this.handleClick);
  }

  componentWillUnmount() {
    document.getElementById('app')
      .removeEventListener('click', this.handleClick);
  }

  handleClick = ({ target }: { target: EventTarget }) => {
    if (!this.containerRef.contains(target)) {
      this.props.onClickOut();
    }
  };

  containerRef: HTMLElement;

  render() {
    const { children, ...rest } = this.props;
    const filteredProps = _.omit(rest, 'onClickOut');

    return (
      <div
        {...filteredProps}
        ref={container => {
          this.containerRef = container;
        }}
      >
        {children}
      </div>
    );
  }
}

export default IxClickOut;

package.json

{
  "name": "verinmueblesmeteor",
  "private": true,
  "scripts": {
    "start": "meteor run",
    "ios": "NODE_ENV=developement meteor run ios"
  },
  "dependencies": {
    "fine-uploader": "^5.10.1",
    "foundation-sites": "^6.2.3",
    "install": "^0.8.1",
    "ix-gm-polygon": "^1.0.11",
    "ix-type-building": "^1.4.4",
    "ix-type-offer": "^1.0.10",
    "ix-utils": "^1.3.7",
    "keymirror": "^0.1.1",
    "meteor-node-stubs": "^0.2.3",
    "moment": "^2.13.0",
    "npm": "^3.10.3",
    "rc-slider": "^3.7.3",
    "react": "^15.1.0",
    "react-addons-pure-render-mixin": "^15.1.0",
    "react-dom": "^15.1.0",
    "react-fileupload": "^2.2.0",
    "react-list": "^0.7.18",
    "react-modal": "^1.4.0",
    "react-redux": "^4.4.5",
    "react-router": "^2.6.0",
    "react-styleable": "^2.2.4",
    "react-textarea-autosize": "^4.0.4",
    "redux": "^3.5.2",
    "redux-form": "^5.3.1",
    "redux-thunk": "^2.1.0",
    "rxjs": "^5.0.0-beta.9",
    "rxjs-es": "^5.0.0-beta.9",
    "socket.io": "^1.4.8"
  },
  "devDependencies": {
    "autoprefixer": "^6.3.6",
    "babel-eslint": "^6.0.4",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-0": "^6.5.0",
    "core-js": "^2.0.0",
    "cssnano": "^3.7.1",
    "eslint": "^2.12.0",
    "eslint-config-airbnb": "^9.0.1",
    "eslint-import-resolver-meteor": "^0.2.3",
    "eslint-plugin-import": "^1.8.1",
    "eslint-plugin-jsx-a11y": "^1.2.2",
    "eslint-plugin-react": "^5.1.1",
    "node-sass": "^3.8.0",
    "postcss-cssnext": "^2.6.0",
    "sasslets-animate": "0.0.4"
  },
  "cssModules": {
    "ignorePaths": [
      "node_modules"
    ],
    "jsClassNamingConvention": {
      "camelCase": true
    },
    "extensions": [
      "scss",
      "sass"
    ],
    "postcssPlugins": {
      "postcss-modules-values": {},
      "postcss-modules-local-by-default": {},
      "postcss-modules-extract-imports": {},
      "postcss-modules-scope": {},
      "autoprefixer": {}
    }
  }
}

.babelrc

{
  "presets": [
    "es2015",
    "react",
    "stage-0"
  ],
  "whitelist": [
      "es7.decorators",
      "es7.classProperties",
      "es7.exportExtensions",
      "es7.comprehensions",
      "es6.modules"
  ],
  "plugins": ["transform-decorators-legacy"]
}

.eslintrc

{
  "parser": "babel-eslint",
  "extends": "airbnb",
  "rules": {
    "no-underscore-dangle": ["error", { "allow": [_id, b_codes_id] }],
  },
  "settings": {
    "import/resolver": "meteor"
  },
  "globals": {
    "_": true,
    "CSSModule": true,
    "Streamy": true,
    "ReactClass": true,
    "SyntheticKeyboardEvent": true,
  }
}
javascript reactjs eslint flowtype
16个回答
133
投票

如果您希望将

propTypes
定义在类声明中,则需要将其定义为静态 getter:

static get propTypes() { 
    return { 
        children: PropTypes.any, 
        onClickOut: PropTypes.func 
    }; 
}

如果想将其定义为对象,则需要在类外部定义,如下所示:

IxClickOut.propTypes = {
    children: PropTypes.any,
    onClickOut: PropTypes.func,
};

此外,最好从

prop-types
导入道具类型,不是
react
,否则你会在控制台中看到警告(为React 16做准备):

import PropTypes from 'prop-types';

133
投票

我知道这个答案很荒谬,但请考虑禁用此规则,直到解决错误或升级工具:

/* eslint-disable react/prop-types */ // TODO: upgrade to latest eslint tooling

或者在 eslintrc 中禁用整个项目:

"rules": {
  "react/prop-types": "off"
}

22
投票

过去几天我遇到了这个问题。正如 Omri Aharon 在上面的回答中所说,为您的 prop 类型添加类似于以下的定义非常重要:

SomeClass.propTypes = {
    someProp: PropTypes.number,
    onTap: PropTypes.func,
};

不要忘记在类之外添加 prop 定义。我会把它放在我的班级的正下方/上方。如果您不确定 PropType 的变量类型或后缀(例如:PropTypes.number),请参阅此 npm 参考。要使用 PropTypes,您必须导入包:

import PropTypes from 'prop-types';

如果出现 linting 错误:

someProp is not required, but has no corresponding defaultProps declaration
,您所要做的就是将
.isRequired
添加到 prop 定义的末尾,如下所示:

SomeClass.propTypes = {
    someProp: PropTypes.number.isRequired,
    onTap: PropTypes.func.isRequired,
};

或添加默认属性值,如下所示:

SomeClass.defaultProps = {
    someProp: 1
};

如果你和我一样,没有经验或者不熟悉reactjs,你也可能会得到这个错误:

Must use destructuring props assignment
。要修复此错误,请在使用道具之前定义它们。例如:

const { someProp } = this.props;

21
投票

看来问题出在

eslint-plugin-react

如果您通过在类中的任何位置解构注释了命名对象,则它无法正确检测

propTypes
中提到的道具。

过去有类似问题


9
投票

安装 prop-types 包 -

npm i prop-types --save
导入它-

import PropTypes from 'prop-types';

然后指定props,我是这样实现的-

Text.propTypes = {
  children: PropTypes.node.isRequired,
};

export default function Text({ children }) {
  return (
    <VStyle className="para">
      <p>{children}</p>
    </VStyle> 
  );
}

还将其添加到您的 eslintrc.json 或 .js 文件中

"rules": {
    "react/prop-types": "off"
  }

6
投票

在新版本的 React 和 Next.js 上,您可以简单地导入 PropTypes,如下所示,

import PropTypes from "prop-types";

并在文件底部添加 defaultProps 和 propTypes,例如,

Post.defaultProps = {
  posts: "",
};

Post.propTypes = {
  posts: PropTypes.string,
};

export default Post;

它应该可以解决您的 eslint 警告。


4
投票

问题:道具验证中缺少“id1”,eslintreact/prop-types

<div id={props.id1} >
    ...
</div>

以下解决方案在功能组件中有效:

let { id1 } = props;

<div id={id1} >
    ...
</div>

希望有帮助。


4
投票

对我来说,升级 eslint-plugin-react 到最新版本 7.21.5 修复了这个问题


4
投票

PropTypes 检查是个好东西,不建议通过设置忽略

您可以使用 vscode React PropTypes 生成扩展自动生成 propTypes:

  1. 选择您的组件名称
  2. 按命令+。 (Windows 为 Ctrl + .)显示代码操作并选择 PropTypesGenerate,或在 macOS 中按 shift + command + alt + P(Windows 为 shift + ctrl + alt + P)
  3. 输入 propType 替换默认类型

3
投票

另一种方法是:


文件:App.js

    ...
        <Component1 key1="abc" />
    ...

文件:Component1.js

1 错误

    function Component1 ({ key1 }) {
        console.log('key1', key1);
    }

2错误

    function Component1 (props) {
        let{ key1 } = props;
        console.log('key1', key1);
    }

3 有效

注意:

prop
而不是
props

    function Component1 (prop) {
        let{ key1 } = prop;
        console.log('key1', key1);
    }

看起来,linter 只检查正确的单词

props
,而不是
prop
或类似的单词。
如果您刚刚开始或快速原型设计,这是一个解决方案。
对于后期或大型项目,定义 proptypes 可能会更好。



2
投票

问题出在handleClick中的流注释中,我删除了它并且工作正常 谢谢@alik


2
投票

我发现 eslint 在我自己从事的项目中过于严格,但对于这个错误,我通过定义接口然后实现来修复它:

interface myInterface: {
  test: string
}

const MyComponent: React.FC<myInterface> = (props: myInterface) => {

2
投票

复制我在类似问题中的回答: https://stackoverflow.com/a/69199304/4290193

对于那些使用

eslint-plugin-react@^7.25.0

React.FC<IProps> 验证规则的人来说,
react/prop-types
似乎已经
解决了
问题。

所以而不是

const Example: React.FC<IProps> = (props: IProps) => ...

更新后现在可以正常工作,不会出现警告

const Example: React.FC<IProps> = (props) => ...

0
投票

功能性 React 组件。定义为对象。我收到此错误是因为我从另一个名称略有不同的对象复制并粘贴了该对象,并且忘记更改 proptypes 对象的名称。

FooterIcons.propTypes = {} -> FooterIcon.propTypes

0
投票

我们可以引入 Children 属性作为组件 props 的一部分,而不是禁用

prop-types
规则,例如:

import React, { Component } from 'react';

export default class ErrorBoundary extends Component<{ children: React.ReactNode }> {
  constructor(props: { children: React.ReactNode }) {
    super(props);

    this.state = { error: null, errorInfo: null };
  }

  componentDidCatch(error: Readonly<unknown>, errorInfo: Readonly<unknown>): void {
    this.setState({ error, errorInfo });
  }

  render(): React.ReactElement | React.ReactNode {
    const { children } = this.props;
    const { error, errorInfo } = this.state as Readonly<Record<string, { componentStack: string }>>;

    if (errorInfo)
      return (
        <details>
          <h3>Oops, error detected.</h3>
          <p>{error?.toString()}</p>
          <p>{errorInfo?.componentStack}</p>
        </details>
      );
    return children;
  }
}

以上是典型的

eslint
错误消失的例子~~

别担心,开心就好~~


0
投票

我在

React JS:18.2.0
遇到了这个问题。配置完成后
.eslintrc.cjs
问题就解决了。配置:

module.exports = {
  root: true,
  env: { browser: true, es2020: true },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react/jsx-runtime',
    'plugin:react-hooks/recommended',
  ],
  ignorePatterns: ['dist', '.eslintrc.cjs'],
  parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
  settings: { react: { version: '18.2' } },
  plugins: ['react-refresh'],
  rules: {
    "react/prop-types": "off",
    "react-refresh/only-export-components": [
      "warn",
      { allowConstantExport: true },
    ],
    "react/jsx-uses-react": 2,
    "react/jsx-uses-vars": "error",
  },
}
© www.soinside.com 2019 - 2024. All rights reserved.