反应组件中的“无法找到名称”错误

我正在将我现有的 React 代码迁移到 TypeScript,我遇到了很多问题,其中之一就是在我创建 .js文件 .ts文件时出现了很多“无法找到名称”的错误。

下面是有问题的代码:

import React from 'react';


const Footer = ({ children, inModal }) => (
<footer className={'tableBottomPanel' + (inModal ? " in-modal" : "") }>
<div>
{children}
</div>
</footer>
);


export default Footer;

<footer></footer>的五行用红色下划线标出,并给出各种错误,这取决于鼠标悬停的位置,例如:

  • 找不到名称“ footer”。
  • “ >”预期
  • 找不到名称“ div”
  • 未终止的正则表达式文字
  • 运算符“ <”不能应用于“ boolean”和“ RegExp”类型

这是我的 tsconfig.json文件:

{
"compilerOptions": {
"outDir": "./dist/", // path to output directory
"sourceMap": true, // allow sourcemap support
"strictNullChecks": true, // enable strict null checks as a best practice
"module": "es6", // specify module code generation
"jsx": "react", // use typescript to transpile jsx to js
"target": "es5", // specify ECMAScript target version
"allowJs": true, // allow a partial TypeScript and JavaScript codebase
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"lib": [
"es6",
"dom"
],
"types": [
"node"
]
},
"include": [
"./src/"
]
}

我非常困惑,希望你能帮助我!

88676 次浏览

Typescript isn't expecting to see JSX in your Typescript file. The easiest way to resolve this is to rename your file from .ts to .tsx.

JSX in Typescript Documentation

I have also come across the same problem. This may be due to the extension you use as .ts file doesn't allow JSX code in it. Instead you should use .tsx extension.

I had this error in a file with no extension. It was simply filename without extensions so VSCode assumed it to be TS. When I renamed my file to filename.js the error went away.

Though, If you want the file to be in typescript and don't want the error, the accepted answer (filename.tsx) is the correct approach.