【发布时间】:2021-06-29 11:54:51
【问题描述】:
我使用 React 和 Chakra-UI 创建了以下上下文提供程序:
import { useBoolean } from "@chakra-ui/react"
import { createContext } from "react"
const MobileContext = createContext<typeof useBoolean | undefined>(undefined)
function MobileProvider({ children }) {
const [show, setShow] = useBoolean(false)
return (
<MobileContext.Provider value={{ show, setShow }}>
{children}
</MobileContext.Provider>
)
}
不幸的是,上面的代码似乎不起作用。我在value={{ show, setShow }} 中的show 下得到一条红色波浪线,并带有以下消息:
Type '{
show: boolean;
setShow: {
readonly on: () => void;
readonly off: () => void;
readonly toggle: () => void;
};
}' is not assignable to type
'(initialState?: InitialState) =>
readonly [
boolean,
{
readonly on: () => void;
readonly off: () => void;
readonly toggle: () => void;
}
]'.
Object literal may only specify known properties, and 'show' does not exist in type
'(initialState?: InitialState) =>
readonly [
boolean,
{
readonly on: () => void;
readonly off: () => void;
readonly toggle: () => void;
}
]'
.ts(2322)
index.d.ts(336, 9):
The expected type comes from property 'value' which is declared here on type
'IntrinsicAttributes & ProviderProps<(initialState?: InitialState) =>
readonly [
boolean,
{
readonly on: () => void;
readonly off: () => void;
readonly toggle: () => void;
}
]
>'
我想我明白问题所在——useBoolean 的返回值与show 和setShow 不完全相同(尽管也许我错了)。无论哪种方式,我都无法弄清楚如何让它正常工作。
有什么想法吗?
谢谢。
【问题讨论】:
标签: reactjs typescript react-context