TypeScript+React项目Eslint报错函数组件不是函数表达式怎么解决?
问题原因
报错来自eslint-plugin-react提供的react/function-component-definition规则,你使用的Airbnb预设默认对函数组件的定义方式有强制要求,你当前的三种写法都不符合它的默认校验规则,因此会触发报错,自动修复后又会和Airbnb的func-names规则(要求函数必须有名称)冲突,才会出现来回报错的情况。
解决方案
在.eslintrc.js的rules字段中添加如下配置,根据你偏好的组件写法调整即可:
方案1:允许使用箭头函数定义组件(匹配你最开始的官方写法)
"react/function-component-definition": [ "error", { "namedComponents": "arrow-function", "unnamedComponents": "arrow-function" } ]
配置后你最开始的写法就不会触发报错:
const Div = ({ text }: DivProps): JSX.Element => (<div>{text}</div>)
方案2:允许使用普通函数声明定义组件
"react/function-component-definition": [ "error", { "namedComponents": "function-declaration", "unnamedComponents": "function-expression" } ]
方案3:允许多种写法同时存在
如果不需要限制组件定义方式,可以直接关闭该规则,或者配置允许多种写法:
// 直接关闭规则 "react/function-component-definition": "off" // 允许多种写法 "react/function-component-definition": [ "error", { "namedComponents": ["function-declaration", "arrow-function", "function-expression"], "unnamedComponents": ["function-expression", "arrow-function"] } ]
ESLint配置优化建议
针对TypeScript+React的开发场景,你的现有配置可以补充以下规则:
- 适配React17+的JSX运行时,不需要每个文件手动导入React:在extends中添加
plugin:react/jsx-runtime,同时关闭react/react-in-jsx-scope规则 - 关闭React原生类型校验规则,使用TypeScript的类型定义替代:添加
"react/prop-types": "off" - 允许导入开发依赖:Airbnb默认不允许导入devDependencies中的包,会导致测试文件、配置文件导入依赖报错,添加
"import/no-extraneous-dependencies": ["error", { "devDependencies": true }] - 调整函数返回值校验规则:如果不需要强制要求每个函数都显式声明返回值,可以添加
"@typescript-eslint/explicit-function-return-type": "off",组件返回值TypeScript会自动推导
内容的提问来源于stack exchange,提问作者Alejandro Aburto
相关产品推荐
相关产品推荐

