typescript - 在 eslint 规则中为 JSX.Element 类型的变量指定 PascalCase 命名约定
问题描述
我想对JSX.Element
我的 React+Typescript 项目中的类型变量强制执行 PascalCase。我经常使用以下模式来创建功能组件,并且我喜欢通过给它一个 PascalCase 名称来区分我的同名导出:
//MyComponent.tsx
//PascalCase for MyComponent
export const MyComponent= (): JSX.Element =>{
return (
<div>
My Component
</div>
)
}
export default MyComponent
使用我当前的 linter 设置,我收到一个警告,即Variable name `MyComponent` must match one of the following formats: camelCase, UPPER_CASE
. 如何在我的 linter 设置中添加一条规则,对 JSX.Element 类型的变量强制执行 PascalCase?
这是我目前的.eslintrc.json
:
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": ["@typescript-eslint", "react-hooks"],
"extends": [
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
"react/prop-types": "off",
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/explicit-function-return-type": [
"warn",
{
"allowExpressions": true
}
]
},
"settings": {
"react": {
"pragma": "React",
"version": "detect"
}
}
}
解决方案
看起来目前在声明时是不可能的(见下面的链接)。但是,不正确的大小写不能扩散到声明它的文件之外,因为小写名称是为诸如 , 等内在类型保留div
的span
。
// my-component.tsx
export const myComponent: FC<{}> = () => (
<div>My Component</div>
);
export default myComponent;
// app.tsx
import { myComponent } from './my-component';
// Fails to compile with: Property 'myComponent' does not
// exist on type 'JSX.IntrinsicElements'. TS2339
const App = (): JSX.Element => <myComponent />;
在默认导出的情况下,声明文件中使用的名称被有效地删除,因为它只是分配给在导入文件中选择的任何名称:
// app.tsx
import SomeOtherName from './my-component';
const App = (): JSX.Element => <SomeOtherName />;
在此处讨论没有特定于 React 组件的规则:typescript-eslint/issues/2607
此外 - 不能保证返回 JSX.Element 的函数实际上是一个反应组件。返回 JSX.Element 但不是反应组件的实用函数是一种相对常见的做法,这会导致误报。
编辑:以下不正确。
import { FC } from 'react';
const MyComponent: FC<{}> = () => {
return (
<div>
My Component
</div>
)
}
推荐阅读
- r - 如何在 CentOS 中安装特定版本的 R 3.3.1
- javascript - 制作 React 状态数组的浅拷贝并修改该浅拷贝是否安全?
- python - 给np数组中的字符串赋值,转换为int,计算加权平均值
- prestashop-1.6 - 在帮助表单 Prestashop 中动态添加表单字段
- android - 如何将变量从 populateViewHolder 传递给 onActivityResult()?
- laravel - 用户的 Laravel 权限问题
- wordpress - 文件上传后联系表格 7 继续旋转
- android - 在 ViewPager 中的 Fragment 之间设置共享元素转换
- javascript - javascript向底层元素添加点击事件
- azure - Azure 数据工厂出站数据传输定价