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

React组件继承Input Props时ESLint误报Prop未校验的解决方法

解决React TypeScript Input组件ESLint value属性未校验问题

这个问题的核心是ESLint的react/prop-types规则默认会检查所有解构出的props,但你已经通过TypeScript接口InputProps继承了React.ComponentPropsWithoutRef<'input'>,TypeScript的类型系统已经完成了props校验,无需再手动添加prop-types定义。以下是几种可行的解决方式:

方式一:全局关闭react/prop-types规则(推荐TS项目使用)

在项目的ESLint配置文件(如.eslintrc.js或.eslintrc.json)中,将该规则设为关闭:

module.exports = {
  // 其他配置项...
  rules: {
    "react/prop-types": "off"
  }
};

对于纯TypeScript的React项目,TypeScript的类型校验已经完全覆盖了prop-types的作用,关闭该规则可以避免冗余的校验提示。

方式二:针对单个组件或代码行禁用规则

如果不想全局关闭规则,可以在组件文件顶部添加注释,禁用当前文件的该规则:

/* eslint-disable react/prop-types */

interface InputProps extends React.ComponentPropsWithoutRef<'input'> {
  // 自定义属性...
}

export const Input = React.forwardRef<HTMLInputElement, InputProps>(
  ({ value, ...rest }, ref) => {
    // 组件逻辑...
  }
);

或者仅在value解构的位置禁用单行规则:

export const Input = React.forwardRef<HTMLInputElement, InputProps>(
  (
    {
      // eslint-disable-next-line react/prop-types
      value,
      ...rest
    },
    ref
  ) => {
    // 组件逻辑...
  }
);

方式三:配置ESLint识别TypeScript类型定义

确保项目已安装@typescript-eslint/eslint-plugin,然后在ESLint配置中启用TypeScript的类型校验规则,替代react/prop-types:

module.exports = {
  // 其他配置项...
  plugins: ["@typescript-eslint"],
  rules: {
    "react/prop-types": "off",
    "@typescript-eslint/typedef": ["error", { props: true }]
  }
};

这种方式会让ESLint依赖TypeScript的类型定义来做props校验,同时关闭冗余的prop-types检查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:50:05