reactjs - React/TS/material-ui 使用变量作为网格属性的值会引发错误:“没有重载匹配”和“类型'数字'不可分配给类型......”
问题描述
tl;dr:xs
当在 JSX中使用变量作为网格属性的值时,material-ui 会引发 TS 错误
我正在使用 React/TypeScript 在 material-ui 中实现网格
我希望特定元素的宽度取决于该元素的数量。
这是一个简单的计算,输出 12 到 4 之间的整数:
const sheets = [0, 1, 2];
const sheetColWidth = sheets.length > 3 ? 3 : 12 / sheets.length;
但是当我使用 sheetColWidth (value 1
, 2
, 3
or 4
, of type number
) 作为网格xs
属性的值时,TS 会抛出一个错误:
No overload matches this call.
Overload 1 of 2, '(props: { component: ElementType<any>; } & Partial<Record<Breakpoint, boolean | 1 | 6 | 3 | 5 | 7 | 10 | "auto" | 2 | 4 | 8 | 9 | 11 | 12>> & { ...; } & CommonProps<...> & Pick<...>): Element', gave the following error.
Type 'number' is not assignable to type 'boolean | 1 | 6 | 3 | 5 | 7 | 10 | "auto" | 2 | 4 | 8 | 9 | 11 | 12 | undefined'.
Overload 2 of 2, '(props: DefaultComponentProps<GridTypeMap<{}, "div">>): Element', gave the following error.
Type 'number' is not assignable to type 'boolean | 1 | 6 | 3 | 5 | 7 | 10 | "auto" | 2 | 4 | 8 | 9 | 11 | 12 | undefined'. TS2769
我在 Codesandbox 上有一个简化的示例:
https://codesandbox.io/s/loving-dust-cli52
(这没有附加样式,因为它们不相关)
当你加载它时,它似乎渲染得很好,但片刻之后,xs
L.18 上的属性得到一个红色的错误下划线,并将鼠标悬停在它上面会显示错误。
在我的应用程序中,该应用程序只是因 TS 错误而崩溃。
用允许的数字替换sheetColWidth
L.18 上的,错误消失,一切都很好。
有点混淆,因为变量的值是 Grid 接口中枚举的允许值之一。
我为它尝试了字符串插值,但后来因为它是一个字符串而被拒绝,因为它应该是:
xs={`${sheetColWidth}`}
我尝试将值转换为字符串然后再转换为数字 - 这没有改变,而且非常正确:
const sheetColWidth = parseInt(sheets.length > 3 ? 3 : 12 / sheets.length + '');
我难住了。
任何见解都非常感谢。
解决方案
您还可以使用库本身中可用的类型:
import { Grid, GridSize } from "@material-ui/core";
// ...
const sheetColWidth: Gridsize = 1;
推荐阅读
- python-3.x - 如何修复我在 Python 中关于系列的数学代码?
- javascript - Vue beforeUpdate 事件为递归组件触发两次
- dart - Flutter - SliverAppBar 中的圆角
- nestjs - NestJs 在多个模块中使用相同的服务实例
- powershell - PowerShell安装NuGet,说无法上网,但我其实可以
- hashset - 受一个命令影响的两个不同的 HashSet 对象(JAVA)
- c - ftell/fseek 与 /sys/class 文件中的实际可读数据长度不同
- java - Android警报管理器每天不工作两次
- domain-driven-design - CQRS 命令和查询。就 DDD 而言,它们属于应用程序级别还是域级别?
- c# - 如何用鼠标在世界画布中拖动精灵?