propType "name" 不是必需的,但没有相应的 defaultProps 声明

DSt*_*man 6 typescript reactjs

我有一个带有可选道具的组件。我通过将可选属性传递给 Card 组件来定义它们的默认值,但 eslint 一直告诉我propType "text" is not required, but has no corresponding defaultProps declaration.属性也是如此childrenwithout defaultProps下面的代码似乎与本页上的示例一致: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-default-props.md

import { ReactElement } from 'react';

interface CardProps {
  title: string,
  text?: string | (string|ReactElement)[],   // eslint is complaining here
  children?: React.ReactNode                 // and here
}

const Card = ({ title, text = '', children = null }: CardProps) => (
    <div className="container">
      <div className="title">{title}</div>
      <div className="underline" />
      <div className="card">
        <div className="text">
          {text}
          {children}
        </div>
      </div>
    </div>
);
Run Code Online (Sandbox Code Playgroud)

我的 eslint (7.32.0) 配置如下:

{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "plugin:react/recommended",
        "airbnb"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "plugins": [
        "react",
        "@typescript-eslint"
    ],
    "rules": {
        "react/jsx-filename-extension": [1, { "extensions": [".ts", ".tsx"] }],
        "react/jsx-uses-react": "off",
        "react/react-in-jsx-scope": "off",
        "import/extensions": [
            "error",
            "ignorePackages",
            {
              "js": "never",
              "jsx": "never",
              "ts": "never",
              "tsx": "never"
            }
        ],
        "no-use-before-define": "off",
        "@typescript-eslint/no-use-before-define": ["error"]
    },
    "settings": {
        "import/resolver": {
            "node": {
            "extensions": [".js", ".jsx", ".ts", ".tsx"]
            }
        }
    },
    "globals": {
        "React": true,
        "JSX": true
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 22

TLDR:关闭规则。

我也在使用 ESLint 7.32.0 (和 TS 4.4.4)并遇到同样的问题。我对此进行了深入研究,并找到了三种阻止 ESLint 消息的方法。

1)

第一种是直接使用defaultProps,这对于函数组件来说是不推荐使用的。在你的情况下,它看起来像:

Card.defaultProps = {
  text: '',
  children: null,
}
Run Code Online (Sandbox Code Playgroud)

在 Card 函数声明之后。但这是一种反模式。

2)

二是导出接口。为什么会起作用仍然是个谜。

3)

第三种是使用React.FC函数输入模式。这有很多缺点,我不使用它,可能出于与您类似的原因。

结论

这些技术都不能令人满意,并且由于 defaultTypes 已被弃用,因此最好关闭 ESLint 规则,而不是根据自己的喜好重新配置代码。

  • 关闭这些行的 linter 将是我的临时解决方案,现在也是我的最终解决方案,哈哈。希望有一天能解决这个问题。无论如何,谢谢。 (2认同)