关于react.js:React报错之Cannot-find-name

3次阅读

共计 2364 个字符,预计需要花费 6 分钟才能阅读完成。

注释从这开始~

.tsx 扩展名

为了在 React TypeScript 中解决 Cannot find name 报错,咱们须要在应用 JSX 文件时应用 .tsx 扩展名,在你的 tsconfig.json 文件中把 jsx 设置为 react-jsx,并确保为你的利用程序安装所有必要的@types 包。

上面是在名为 App.ts 的文件中产生谬误的示例。

export default function App() {// ⛔️ 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,咱们必须:

  1. 将文件命名为 .tsx 扩展名;
  2. 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", // 👈️ 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/

在我的项目的根目录下关上终端,运行上面的命令:

# 👇️ with NPM
npm install --save-dev @types/react @types/react-dom @types/node @types/jest typescript

# ------------------------------------------------------

# 👇️ with YARN
yarn add @types/react @types/react-dom @types/node @types/jest typescript --dev

该命令装置了reactreact-domnodejest 的类型申明文件,同时也装置了typescript

如果仍旧报错,请尝试删除 node_modulespackage-lock.json(不是package.json)文件,从新运行npm install 并重启 IDE。

# 👇️ delete node_modules and package-lock.json
rm -rf node_modules
rm -f package-lock.json

# 👇️ 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

或者装置上面依赖的最新版:

# 👇️ with NPM
npm install --save-dev @types/react@latest @types/react-dom@latest @types/node@latest @types/jest@latest typescript@latest

# ------------------------------------------------------

# 👇️ with YARN
yarn add @types/react@latest @types/react-dom@latest @types/node@latest @types/jest@latest typescript@latest --dev
正文完
 0