You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件已设参数解构默认值仍触发ESLint require-default-props报错如何解决?

报错原因

你当前使用的eslint-plugin-react版本中,react/require-default-props规则默认仅识别组件静态defaultProps声明,不支持参数解构时设置的默认值校验,因此会触发误报。


解决方案

有两种常用方式可以消除报错,可根据项目习惯选择:

方案1:调整ESLint规则配置(推荐,符合现代React写法习惯)

在你的ESLint配置的rules字段中新增如下配置,告诉规则函数组件参数解构的默认值属于合法的默认声明:

"react/require-default-props": ["error", {
  "functions": "defaultArguments"
}]

如果是纯TypeScript项目,也可以直接关闭该规则:TypeScript的可选类型+解构默认值已经可以完整覆盖默认值校验能力,不需要保留JS生态的旧规则,配置如下:

"react/require-default-props": "off"

修改配置后重启ESLint服务即可生效。

注意:如果你的eslint-plugin-react版本低于7.23.0,不支持functions配置项,要么升级插件版本,要么使用方案2。

方案2:补充静态defaultProps声明(无需修改ESLint配置)

如果不想调整规则,按照老规则要求给组件补充静态defaultProps即可,修改后的代码如下:

import { ReactElement } from 'react';

interface CardProps {
  title: string,
  text?: string | (string|ReactElement)[],
  children?: React.ReactNode
}

const Card = ({ title, text, children }: CardProps) => (
    <div className="container">
      <div className="title">{title}</div>
      <div className="underline" />
      <div className="card">
        <div className="text">
          {text}
          {children}
        </div>
      </div>
    </div>
);

Card.defaultProps = {
  text: '',
  children: null
}

export default Card;

内容的提问来源于stack exchange,提问作者DSteman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 12:39:00