Nextjs issue - Property children does not exist on type {}
P粉658954914
P粉658954914 2023-08-16 20:20:47
0
1
557
<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粉658954914
P粉658954914

reply all(1)
P粉495955986

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!