React函数组件触发react/function-component-definition lint错误的解决方案咨询
解决React函数组件的
react/function-component-definition Lint错误 你遇到的错误是因为ESLint的react/function-component-definition规则要求函数组件必须使用函数声明的形式定义,而你当前用了箭头函数来定义组件,所以触发了lint报错。下面提供两种可行的解决方案:
方案一:将组件改为函数声明式定义
直接把箭头函数换成function声明的写法,符合规则要求,修改后的代码如下:
import { FieldProps, getIn } from "formik"; import React from "react"; import { TextField, TextFieldProps } from "@mui/material"; export function FormTextField({ error, helperText, field, form, ...rest }: FieldProps & TextFieldProps) { const isTouched = getIn(form.touched, field.name); const errorMessage = getIn(form.errors, field.name); return ( <TextField variant="outlined" fullWidth error={error ?? Boolean(isTouched && errorMessage)} helperText={ helperText ?? (isTouched && errorMessage ? errorMessage : undefined) } {...rest} {...field} /> ); }
注意:记得补充导入TextFieldProps,否则会出现类型未定义的报错
方案二:修改ESLint规则,允许箭头函数定义
如果不想改动组件写法,可以调整ESLint配置,让规则允许使用箭头函数定义命名组件。在你的ESLint配置文件(如.eslintrc.js、.eslintrc.json)中添加或修改以下规则:
{ "rules": { "react/function-component-definition": [ "error", { "namedComponents": ["arrow-function", "function-declaration"], "unnamedComponents": ["arrow-function", "function-expression"] } ] } }
配置后,ESLint会同时接受函数声明和箭头函数两种组件定义方式,你的原代码就能正常通过lint检查了。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

