我整个早上都在努力解决这个问题,但无法在任何地方找到解决方案。我是 typescript 的新手,正在尝试使用 Eslint 和 Prettier 正确设置它,以确保代码格式正确。
所以,当我创建功能组件时遇到的问题是,根据“cheatsheet” ,我正在尝试导出一个简单的组件,例如:
import React from "react";
type DivProps = {
text: string;
};
const Div = ({ text }: DivProps): JSX.Element => (<div>{text}</div>)
export default Div;
然而,eslint在抱怨,说“函数组件不是函数表达式”。
运行修复时,它将我的函数转换为一个无名函数:
const Div = function ({ text }: DivProps): JSX.Element {
return <div>{text}</div>;
};
然后它会抱怨说“未预期的未命名函数”。
即使我尝试重构函数为:
function Div({ text }: DivProps): JSX.Element {
return <div>{text}</div>;
};
我仍然收到相同的错误,提示“Function component is not a function expression”。
我的.eslintrc.js文件如下:
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: ["airbnb", "plugin:@typescript-eslint/recommended", "prettier"],
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: "module",
},
plugins: ["@typescript-eslint", "react-hooks", "prettier"],
rules: {
"react-hooks/rules-of-hooks": "error",
"prettier/prettier": "error",
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": ["error"],
"react/jsx-filename-extension": [
1,
{
extensions: [".tsx"],
},
],
"import/prefer-default-export": "off",
"import/extensions": [
"error",
"ignorePackages",
{
ts: "never",
tsx: "never",
},
],
},
settings: {
"import/resolver": {
typescript: {},
},
},
};
希望能得到任何关于此事的帮助!
PS:如果您在 eslintrc 文件中看到任何需要修改/改进的地方,请让我知道。正如我所提到的,我是 TypeScript 的新手,因此仍在尝试找到最佳的代码检查选项。
谢谢!
Alejandro
FC
类型吗?const Div:FC<Props>=(props)=>null
。你可以直接从 'react' 导入FC
。 - captain-yossarian from Ukraine