[英]Type Children Element is missing properties with Nextjs + React Context with TypeScript
Using Reacts Context with Nextjs and TypeScript is showing a vague error wrapping context around the _app.tsx
.使用带有 Nextjs 和 TypeScript 的 Reacts Context 在
_app.tsx
周围显示一个模糊的错误包装上下文。
Event though I am passing in the values to the Context Provider it's giving me the error:事件虽然我将值传递给上下文提供程序,但它给了我错误:
"Type '{ children: Element; }' is missing the following properties from type 'ContextProps': capturedPokemons, catchPokemon, releasePokemon" “类型 '{ children: Element; }' 缺少来自类型 'ContextProps' 的以下属性:cappedPokemons、catchPokemon、releasePokemon”
Here is my _app.tsx
这是我的
_app.tsx
function MyApp({ Component, pageProps }: AppProps) {
return (
<CaughtProvider>
<Component {...pageProps} />
</CaughtProvider>
);
}
Here is the Context:这是上下文:
type PokemonProps = {
number: string;
name: string;
image: string;
};
type ContextProps = {
capturedPokemons: PokemonProps[];
catchPokemon: (newPokemon: PokemonProps[]) => void;
releasePokemon: (id: string) => void;
};
const CaughtContext = createContext<ContextProps>({
capturedPokemons: [],
catchPokemon: () => undefined,
releasePokemon: () => undefined,
});
export const useCaught = () => useContext(CaughtContext);
export const CaughtProvider: React.FC<ContextProps> = ({ children }) => {
const [capturedPokemons, setCapturedPokemons] = useState<any>([]);
const catchPokemon = (newPokemon: PokemonProps[]) => {
if (capturedPokemons.length >= 6) {
alert('You cannot carry any more Pokemon.');
return;
}
const alreadyCaptured = capturedPokemons.some(
(p: PokemonProps) => p.name === newPokemon[0].name
);
if (alreadyCaptured) {
alert('you already have that pokemon');
return;
}
if (window.confirm('Capture Pokemon')) {
setCapturedPokemons([...capturedPokemons, ...newPokemon]);
}
};
return (
<CaughtContext.Provider
value={{ catchPokemon, capturedPokemons, releasePokemon }}>
{children}
</CaughtContext.Provider>
);
};
The app works fine as expected and as I'm aware this is how it's done in plain React/JS without TypeScript.该应用程序按预期工作正常,我知道这是在没有 TypeScript 的普通 React/JS 中完成的。
You need to have a separate type for the CaughtProvider
您需要为
CaughtProvider
提供一个单独的类型
type CaughtProviderProps = {
children: React.ReactNode
}
and use it as并将其用作
CaughtProvider: React.FC<CaughtProviderProps>
ContextProps
is for your context value
so its not right to use it for CaughtProvider
. ContextProps
用于您的context value
,因此将其用于CaughtProvider
是不正确的。 CaughtProvider
is just a component which takes the children
prop. CaughtProvider
只是一个使用children
属性的组件。 So its better to have a separate type for it.所以最好有一个单独的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.