在typescript中使用createContext时出错



我正试图使一个上下文与钩子在反应与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>
)
}

但是不知道为什么,返回得到这样的问题

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

和i不能声明StateGlobalContext。提供程序,错误消息如下

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

同时,与其将函数的返回类型声明为React.FC<ReactNode>,不如将组件本身声明为React.FC<StateGlobalProviderProps>类型

相关内容

  • 没有找到相关文章

最新更新