【发布时间】:2021-08-21 06:40:43
【问题描述】:
将 Reacts Context 与 Nextjs 和 TypeScript 一起使用会显示围绕 _app.tsx 包装上下文的模糊错误。
事件虽然我将值传递给上下文提供程序,但它给了我错误:
“类型 '{ children: Element; }' 缺少类型 'ContextProps' 中的以下属性:capturedPokemons、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 中完成的。
【问题讨论】:
标签: reactjs typescript next.js