React 的 useState() setter 的 Typescript 类型
我正在尝试创建 React Context,其中参数 mode
和 setMode
是 React 状态的 getter 和 setter。这是为了能够从子组件更新 css 模式(亮/暗)。
我收到 ColorModeContext
的 value
的 Typescript 错误(我猜,因为这行接口 AppContextInterface
不正确:setMode: (c: string) => void)
:
function App() {
interface AppContextInterface {
mode: string;
setMode:(c: string) => void
}
const ColorModeContext = React.createContext<AppContextInterface>({
mode: 'dark', // set a default value
setMode: () => {},
})
const [mode, setMode] = React.useState<PaletteMode>('dark');
// Update the theme only if the mode changes
const theme = React.useMemo(() => createTheme(getTheme(mode)), [mode]);
return (
<ColorModeContext.Provider value= {{ mode, setMode }}>
<ThemeProvider theme={theme}>
<div>
</ChildComponent>
</div>
</ThemeProvider>
</ColorModeContext.Provider>
);
}
export default App;
我该如何修复它?谢谢
I'm trying to create React Context which parameters mode
and setMode
with are getter and setter of a React state. This is needed to be able to update the css mode (light / dark) from child components.
I'm getting this Typescript error for value
of ColorModeContext
(I guess, because this line of interface AppContextInterface
is incorrect: setMode:(c: string) => void)
:
function App() {
interface AppContextInterface {
mode: string;
setMode:(c: string) => void
}
const ColorModeContext = React.createContext<AppContextInterface>({
mode: 'dark', // set a default value
setMode: () => {},
})
const [mode, setMode] = React.useState<PaletteMode>('dark');
// Update the theme only if the mode changes
const theme = React.useMemo(() => createTheme(getTheme(mode)), [mode]);
return (
<ColorModeContext.Provider value= {{ mode, setMode }}>
<ThemeProvider theme={theme}>
<div>
</ChildComponent>
</div>
</ThemeProvider>
</ColorModeContext.Provider>
);
}
export default App;
How can I fix it? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您的
useState
类型被定义为PaletteMode
,因此您需要在上下文的界面中定义相同的内容。此外,您还可以使用与定义 setState 操作相同的类型(可以从 React 导入):Since your
useState
type is defined asPaletteMode
you need to define the same thing in your context's interface. In addition, you can also use the same types used to define thesetState
action (which you can import from React):