Nextjs問題 - 類型{}上不存在屬性children
P粉658954914
P粉658954914 2023-08-16 20:20:47
0
1
556
<p>我正在使用React和Next.js,以下是我的程式碼,它在<code>children</code>屬性上拋出一個錯誤,錯誤訊息為<strong>屬性children在類型{}上不存在</strong></p> <pre class="brush:php;toolbar:false;">import { NextPage } 從 "next"; import { createContext, useContext, useReducer, Dispatch } from "react"; import { GlobalStatesType } from "../types"; import reducer, { ActionType, initialState } from "../reducers"; export const StateContext = createContext<{ states: GlobalStatesType; dispatch: Dispatch<ActionType>; }>({ states: initialState, dispatch: () => {}, }); export const StateProvider: NextPage = ({ children }) => { const [states, dispatch] = useReducer(reducer, initialState); return ( <StateContext.Provider value={{ states, dispatch }}> { children } </StateContext.Provider> ); }; export const useStatesValue = () => useContext(StateContext);</pre> <p>如何在我導入的next函數的上下文中寫程式碼? </p>
P粉658954914
P粉658954914

全部回覆(1)
P粉495955986

看起來你正在使用TypeScript和Next.js建立一個上下文提供者元件。你遇到的錯誤"屬性'children'在類型'{}'上不存在",很可能是因為TypeScript在函數元件中無法辨識children屬性。

要解決這個問題,你可以在StateProvider元件中明確定義children屬性的類型。以下是如何做到這一點:

import { NextPage } from "next";
import { createContext, useContext, useReducer, Dispatch, ReactNode } from "react"; // 导入ReactNode类型

import { GlobalStatesType } from "../types";
import reducer, { ActionType, initialState } from "../reducers";

type StateProviderProps = {
  children: ReactNode; // 定义children属性的类型
};

export const StateContext = createContext<{
  states: GlobalStatesType;
  dispatch: Dispatch<ActionType>;
}>({
  states: initialState,
  dispatch: () => {},
});

export const StateProvider: NextPage<StateProviderProps> = ({ children }) => { // 使用StateProviderProps类型
  const [states, dispatch] = useReducer(reducer, initialState);

  return (
    <StateContext.Provider value={{ states, dispatch }}>
      {children} {/* 直接使用children */}
    </StateContext.Provider>
  );
};

export const useStatesValue = () => useContext(StateContext);

透過定義StateProviderProps類型並使用它來指定StateProvider元件中children屬性的類型,你將不再遇到與children屬性相關的TypeScript錯誤。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!