Typescript - React 组件中的“找不到名称”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51158080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript - "Cannot find name" errors in React components
提问by noblerare
I am migrating my existing React code over to TypeScript and I am hitting a lot of issues, one of them being a lot of "Cannot find name" errors when I make my .js
files .ts
files.
我正在将现有的 React 代码迁移到 TypeScript,但遇到了很多问题,其中之一是在我制作.js
文件时出现很多“找不到名称”错误.ts
。
Here is the code in question:
这是有问题的代码:
import React from 'react';
const Footer = ({ children, inModal }) => (
<footer className={'tableBottomPanel' + (inModal ? " in-modal" : "") }>
<div>
{children}
</div>
</footer>
);
export default Footer;
The five lines from <footer>
to </footer>
are underlined in red and give me various errors, depending where I hover my mouse, such as:
从<footer>
to 开始的五行</footer>
用红色下划线标出并给我各种错误,这取决于我将鼠标悬停在哪里,例如:
- Cannot find name 'footer'.
- '>' expected
- Cannot find name 'div'
- Unterminated regular expression literal
- Operator '<' cannot be applied to types 'boolean' and 'RegExp'
- 找不到名称“页脚”。
- '>' 预期
- 找不到名称“div”
- 未终止的正则表达式文字
- 运算符 '<' 不能应用于类型 'boolean' 和 'RegExp'
Here is my tsconfig.json
file:
这是我的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/"
]
}
I am incredibly confused and would greatly appreciate some help!
我非常困惑,非常感谢一些帮助!
回答by coreyward
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
.
Typescript 不希望在您的 Typescript 文件中看到 JSX。解决这个最简单的方法是从重命名文件.ts
到.tsx
。
回答by Sachin
I have also come across the same problem. This may be due to the extension you use as .ts don't allow to write JSX code in it. Instead using .ts extension you should use .tsx extension
我也遇到了同样的问题。这可能是由于您使用的扩展名 .ts 不允许在其中编写 JSX 代码。您应该使用 .tsx 扩展名,而不是使用 .ts 扩展名