将 createContext 与打字稿一起使用时出错

Get error when using createContext with typescript

我正在尝试创建一个带有钩子的上下文,以便像这样与打字稿做出反应:

// StateGlobalContext.ts
import React, { Dispatch, ReactNode, SetStateAction } from "react";

export interface StateGlobalContextType {
  loading: boolean
  setLoading: Dispatch<SetStateAction<boolean>>
}

export const StateGlobalContext = React.createContext<StateGlobalContextType>({} as StateGlobalContextType);

export default function StateGlobalProvider({ children: ReactNode }): React.FC<ReactNode> {
  const [loading, setLoading] = React.useState<boolean>(false);

  return (
    <StateGlobalContext.Provider value={{ loading, setLoading }}>
      {props.children}
    </StateGlobalContext.Provider>
  )
}

但不知为何,return遇到这样的问题

Type '{}' is missing the following properties from type 'ReactElement<any, any>': type, props, key

而且我无法声明StateGlobalContext.Provider,这样的错误信息

Cannot find namespace 'StateGlobalContext'

这是一个错误,与您处理道具输入的方式有关。

当在 Typescript 中进行解构时,{ children: ReactNode } 会解构 props 中的 children 属性,并将其分配给名为 ReactNode 的变量。然后,不是调用 ReactNode(这仍然是一个错误,因为您也导入了它),而是使用未定义的 props.children

改为使用语法:{ children }: { children: ReactNode },尽管如果使用接口会更容易。

import React, { Dispatch, ReactNode, SetStateAction, createContext } from "react"

export interface StateGlobalContextType {
    loading: boolean
    setLoading: Dispatch<SetStateAction<boolean>>
}

export const StateGlobalContext = createContext<StateGlobalContextType>({} as StateGlobalContextType)

interface StateGlobalProviderProps {
    children: ReactNode
}
const StateGlobalProvider: React.FC<StateGlobalProviderProps> = ({ children }: StateGlobalProviderProps) => {
    const [loading, setLoading] = React.useState<boolean>(false)

    return <StateGlobalContext.Provider value={{ loading, setLoading }}>{children}</StateGlobalContext.Provider>
}

export default StateGlobalProvider

此外,不要将 return 类型的函数声明为 React.FC<ReactNode>,而是将组件本身声明为 React.FC<StateGlobalProviderProps>

类型