将Reacts Context与Nextjs和TypeScript一起使用时,在_app.tsx
周围包装上下文时显示了一个模糊的错误。
事件,尽管我将值传递给上下文提供程序,但它给了我错误:
"类型"{children:Element;}"缺少类型"ContextProps"中的以下属性:capturedPokemon、catchPokemon、releasePokemon">
这是我的_app.tsx
function MyApp({ Component, pageProps }: AppProps) {
return (
<CaughtProvider>
<Component {...pageProps} />
</CaughtProvider>
);
}
上下文如下:
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>
);
};
该应用程序运行良好,正如我所知,这就是在没有TypeScript的情况下使用普通React/JS的方式。
您需要有一个单独的CaughtProvider
类型
type CaughtProviderProps = {
children: React.ReactNode
}
并将其用作
CaughtProvider: React.FC<CaughtProviderProps>
ContextProps
用于您的context value
,因此将其用于CaughtProvider
是不对的。CaughtProvider
只是一个采用children
道具的组件。所以最好有一个单独的类型。