【问题标题】:Type Children Element is missing properties with Nextjs + React Context with TypeScriptType Children 元素缺少 Nextjs + React Context 和 TypeScript 的属性
【发布时间】: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


    【解决方案1】:

    CaughtProvider 需要有一个单独的类型

    type CaughtProviderProps = {
    children: React.ReactNode
    }
    

    并将其用作

    CaughtProvider: React.FC<CaughtProviderProps>
    

    ContextProps 是为您的 context value 使用的,因此将其用于 CaughtProvider 是不正确的。 CaughtProvider 只是一个采用 children 属性的组件。所以最好有一个单独的类型。

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 2015-12-02
      • 2018-06-01
      • 2021-05-07
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 2013-09-04
      相关资源
      最近更新 更多