search

Home  >  Q&A  >  body text

Nextjs issue - Property children does not exist on type {}

<p>I'm using React and Next.js, below is my code, it throws an error on the <code>children</code> attribute, the error message is <strong>Property children in type {} does not exist</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>How do I write the code in the context of the next function I imported? </p>
P粉658954914P粉658954914456 days ago590

reply all(1)I'll reply

  • P粉495955986

    P粉4959559862023-08-17 10:03:15

    It looks like you are using TypeScript and Next.js to create a context provider component. The error "Property 'children' does not exist on type '{}'" that you encounter is most likely because TypeScript does not recognize the children property in a function component.

    To solve this problem, you can explicitly define the type of the children attribute in the StateProvider component. Here's how to do it:

    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);

    By defining the StateProviderProps type and using it to specify the type of the children property in the StateProvider component, you will no longer encounter TypeScript errors related to the children property.

    reply
    0
  • Cancelreply