Nextjs问题 - 类型{}上不存在属性children
P粉658954914
P粉658954914 2023-08-16 20:20:47
0
1
566
<p>我正在使用React和Next.js,以下是我的代码,它在<code>children</code>属性上抛出一个错误,错误信息为<strong>属性children在类型{}上不存在</strong></p> <pre class="brush:php;toolbar:false;">import { NextPage } from "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学习者快速成长!