使用反应创建上下文时无法找到命名空间“ctx”错误 - typescript

2024-03-21

我正在做一个项目react using typescript我很难弄清楚为什么会发生这个错误,基本上,我不能使用任何createContext因此我在互联网上找到了一些例子。 这是我从这里特别得到的:https://github.com/typescript-cheatsheets/react-typescript-cheatsheet https://github.com/typescript-cheatsheets/react-typescript-cheatsheet我正在尝试使用上下文部分中显示的相同内容。

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在行中:

        return <ctx.Provider value={{ state, update }} {...props} />;

我仍然无法弄清楚为什么,有人可以看看我在这里做错了什么吗?这是我的 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.

因此 TypeScript 正在解释<ctx.Provideras 并尝试找到一种类型Provider在命名空间中ctx.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用反应创建上下文时无法找到命名空间“ctx”错误 - typescript 的相关文章

随机推荐