最佳答案
我正在使用 typescript
做一个 react
的项目,但是我不知道为什么会出现这个错误,基本上,我不能使用任何我在互联网上找到的 createContext
的例子,因为这个。
我特别从这里得到的一个: 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"
]
}
如果你能帮忙,我会很感激的!