我正在做一个 typescript React 项目,并尝试编写一些实用程序类。我在以这种方式返回 React 组件时遇到问题,并且不确定我应该做什么/什么是最佳实践。我得到“指的是一个值,但在这里被用作类型”。除非我使用 tsx 文件,否则会出现错误,在这种情况下无法正确导入。另外值得注意的是,抛出 @ts-ignore 可以缓解该错误,但随后会出现“未终止的正则表达式文字”错误
编辑:这是 <SomeIcon />
的错误等等
这是我的 BoxUtils.ts
export abstract class BoxUtils {
public static getIconForStatus(box: BoxModel): Icon | null {
switch(box.status) {
case 'StatusOne':
return <SomeIcon />;
case 'StatusTwo':
return <SomeOtherIcon />;
case 'StatusThree':
return <YetAnotherIcon />;
default:
return null;
}
}
}
这是我使用该实用程序的片段:
<div>{BoxUtils.getIconForStatus(row)}</div>
最佳答案
您在以下几行中包含的语法是 JSX 语法,这意味着它们包含未构建到 Typescript 语言解释器中的 ES6 组件。
return <SomeIcon />;
return <SomeOtherIcon />;
return <YetAnotherIcon />;
但是,您可以通过将文件标记为 .tsx
而不是 .ts
来包含这些语法功能。如果您仅包含 typescript 函数或类型,则可以仅使用 .ts
文件扩展名。
关于reactjs - Typescript Utils 类返回 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65582433/