首页 > 其他分享 >React报错之Cannot find namespace context

React报错之Cannot find namespace context

时间:2022-08-14 21:58:25浏览次数:52  
标签:node react namespace React json 报错 true types latest

正文从这开始~

总览

在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig.json文件中把jsx设置为react-jsx,并确保为你的应用程序安装所有必要的@types包。

cannot-find-namespace-context.png

这里有个例子来展示错误是如何发生的。

// App.ts
import React from 'react';

interface UserCtx {
  first: string;
  last: string;
  age: number;
}

const AuthContext = React.createContext<UserCtx | null>(null);

const authContext: UserCtx = {
  first: 'James',
  last: 'Doe',
  age: 30,
};

const App = () => {
  // ⛔️ Cannot find namespace 'AuthContext'.ts(2503)
  return (
    <AuthContext.Provider value={authContext}>
      <h2>Your app here</h2>
    </AuthContext.Provider>
  );
};

export default App;

上述代码片段的问题在于,文件的扩展名为.ts ,但是我们在里面编写JSX代码。

tsx

这是不被允许的,因为为了能在TypeScript文件中使用JSX,我们必须这样做:

  1. .tsx扩展名命名文件
  2. tsconfig.json文件中开启jsx选项

确保所有你编写JSX代码的文件都有.tsx扩展名。

// App.tsx
import React from 'react';

interface UserCtx {
  first: string;
  last: string;
  age: number;
}

const AuthContext = React.createContext<UserCtx | null>(null);

const authContext: UserCtx = {
  first: 'James',
  last: 'Doe',
  age: 30,
};

const App = () => {
  return (
    <AuthContext.Provider value={authContext}>
      <h2>Your app here</h2>
    </AuthContext.Provider>
  );
};

export default App;

更新完文件的扩展名为.tsx后,如果问题仍未解决,请尝试重启你的IDE和开发服务器。

打开tsconfig.json文件,并确保jsx选项被设置为react-jsx

// tsconfig.json
{
  "compilerOptions": {
    "jsx": "react-jsx", // 

标签:node,react,namespace,React,json,报错,true,types,latest
From: https://www.cnblogs.com/chuckQu/p/16586443.html

相关文章