React报错之Cannot find name
正文从这开始~
.tsx扩展名
为了在react TypeScript中解决Cannot find name报错,我们需要在使用 JSX 文件时使用 .tsx 扩展名,在你的 tsconfig.json 文件中把 jsx 设置为 react-jsx ,并确保为你的应用程序安装所有必要的 @types 包。

下面是在名为 App.ts 的文件中发生错误的示例。
export default function App() {
// :no_entry:️ Cannot find name 'div'.ts(2304)
return (
<div>
<input type="text" id="message" value="Initial value" />
{/* Cannot find name 'button'.ts(2304) */}
<button>Click</button>
</div>
);
}上述示例代码的问题在于,我们的文件扩展名为 .ts ,但是我们在里面却写的 JSX 代码。
这是不被允许的,因此为了在TS文件中使用JSX,我们必须:
- 将文件命名为 .tsx 扩展名;
- 在 tsconfig.json 中启用 jsx 选项。
确保编写JSX代码的所有文件拥有 .tsx 扩展名。
// App.tsx
export default function App() {
return (
<div>
<input type="text" id="message" value="Initial value" />
<button>Click</button>
</div>
);
}如果在更新文件扩展名为 .tsx 后,问题依然没有解决,请尝试重启IDE和开发服务器。
tsconfig.json配置文件
打开 tsconfig.json 文件,确保 jsx 选项设置为 react-jsx 。
{
"compilerOptions": {
"jsx": "react-jsx", // :point_left:️ make sure you have this
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"include": ["src/**/*"]
}当 jsx 选项设置为 react-jsx ,它会导致编译器使用JSX,将 .js 文件改为 _jsx 调用 。
安装@types依赖包
另一个导致Cannot find name错误的原因是,我们没有安装必要的 @types/ 包 。
在项目的根目录下打开终端,运行下面的命令:
# :point_down:️ with npm
npm install --save-dev @types/react @types/react-dom @types/node @types/jest typescript
# ------------------------------------------------------
# :point_down:️ with YARN
yarn add @types/react @types/react-dom @types/node @types/jest typescript --dev该命令安装了 react , react-dom , node , jest 的类型声明文件,同时也安装了 typescript 。
如果依旧报错,请尝试删除 node_modules 和 package-lock.json (不是 package.json )文件,重新运行 npm install 并重启IDE。
# :point_down:️ delete node_modules and package-lock.json
rm -rf node_modules
rm -f package-lock.json
# :point_down:️ clean npm cache
npm cache clean --force
npm install如果错误依旧存在,请确保重启IDE和开发服务器。VSCode经常出现故障,有时重新启动就能解决问题。
如果问题依旧存在,打开 package.json 文件,确保下面的依赖包被包含在 devDependencies 对象中。
{
// ... rest
"devDependencies": {
"@types/react": "^17.0.44",
"@types/react-dom": "^17.0.15",
"@types/jest": "^27.4.1",
"@types/node": "^17.0.23",
"typescript": "^4.6.3"
}
}可以手动添加上述依赖,并重新运行 npm install 。
npm install或者安装下面依赖的最新版:
# :point_down:️ with NPM
npm install --save-dev @types/react@latest @types/react-dom@latest @types/node@latest @types/jest@latest typescript@latest
# ------------------------------------------------------
# :point_down:️ with YARN
yarn add @types/react@latest @types/react-dom@latest @types/node@latest @types/jest@latest typescript@latest --dev来自:https://bobbyhadz.com/blog/react-typescript-cannot-find-name
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!