使用react创建上下文时找不到命名空间'ctx'错误-Typescript [英] Cannot find namespace 'ctx' error when creating Context with react - typescript
问题描述
我正在使用typescript
在react
上开发项目,但是我很难弄清楚为什么会发生此错误,基本上,我不能使用我在其中找到的任何createContext
示例因此,互联网.
我特别是从这里得到的: https://github.com/typescript-cheatsheets/react -typescript-cheatsheet 我正在尝试使用内容"部分中显示的内容.
I'm working on a project with react
using typescript
and I'm having a bad time figuring out why this error is happening, basically, I can't use any createContext
examples that I found on the internet because of this.
This one specifically I got from here: https://github.com/typescript-cheatsheets/react-typescript-cheatsheet I'm trying to use the same that is showing in the Context section.
import * as React from "react";
export function createCtx<A>(defaultValue: A) {
type UpdateType = React.Dispatch<React.SetStateAction<typeof defaultValue>>;
const defaultUpdate: UpdateType = () => defaultValue;
const ctx = React.createContext({
state: defaultValue,
update: defaultUpdate
});
function Provider(props: React.PropsWithChildren<{}>) {
const [state, update] = React.useState(defaultValue);
return <ctx.Provider value={{ state, update }} {...props} />;
}
return [ctx, Provider] as [typeof ctx, typeof Provider];
}
问题在于每次它说存在此错误时
在以下行中找不到名称空间ctx
:
The issue is that everytime it says that there's this error
Cannot find namespace ctx
in the line:
return <ctx.Provider value={{ state, update }} {...props} />;
我仍然无法弄清楚为什么,有人可以看看我在这里做错了什么吗?这是我的tsconfig.json:
I'm still not able to figure out why, someone can see if I'm doing something wrong here? This is my tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"noImplicitAny": false,
"strictNullChecks": false
},
"include": [
"src"
]
}
任何帮助将不胜感激!
推荐答案
您的文件扩展名很可能是.ts
而不是.tsx
.
Your file extension is most likely .ts
instead of .tsx
.
因此,TypeScript将<ctx.Provider
解释为强制转换,并尝试在名称空间ctx
中找到类型Provider
.
Therefore TypeScript is interpreting <ctx.Provider
as cast and tries to find a type Provider
in the namespace ctx
.
这篇关于使用react创建上下文时找不到命名空间'ctx'错误-Typescript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!