【发布时间】:2021-09-11 17:22:34
【问题描述】:
我使用 React createContext 创建了以下上下文:
import { useBoolean } from "@chakra-ui/react"
import { createContext, FC } from "react"
type useBooleanReturn = ReturnType<typeof useBoolean>
export const MobileContext = createContext<
[show: useBooleanReturn[0], setShow: useBooleanReturn[1]] | undefined
>(undefined)
// --- PROVIDER
const MobileProvider: FC = ({ children }) => {
const [show, setShow] = useBoolean(false)
return (
<MobileContext.Provider value={[show, setShow]}>
{children}
</MobileContext.Provider>
)
}
export default MobileProvider
据我所知,这可以正常工作(至少我没有收到任何打字稿错误)。
我现在想按如下方式“使用”该上下文:
import * as React from "react"
import MobileProvider, { MobileContext } from "./context.mobile"
const Mobile = () => {
const [show, setShow] = React.useContext(MobileContext)
...
}
export default Mobile
我在这里遇到了一些打字错误——特别是,[show, setShow] 带有红色波浪线下划线和以下消息:
Type '[
show: boolean,
setShow: {
readonly on: () => void;
readonly off: () => void;
readonly toggle: () => void;
}
] | undefined' is not an array type.ts(2461)
我不明白为什么这不是数组类型或如何解决这个问题。
有什么想法吗?
谢谢。
【问题讨论】:
标签: reactjs typescript react-context use-context