Javascript 带有类型脚本/反应/材质UI的全局主题
我正在为我的应用程序创建全局主题 我的根组件应该提供全局主题:Javascript 带有类型脚本/反应/材质UI的全局主题,javascript,reactjs,typescript,material-ui,Javascript,Reactjs,Typescript,Material Ui,我正在为我的应用程序创建全局主题 我的根组件应该提供全局主题: const themeInstance = { backgroundColor: 'cadetblue' } render ( <ThemeProvider theme={themeInstance}> <ChildComponent /> </ThemeProvider>, rootNode ) const themeInstance={ 背景颜色:
const themeInstance = {
backgroundColor: 'cadetblue'
}
render (
<ThemeProvider theme={themeInstance}>
<ChildComponent />
</ThemeProvider>,
rootNode
)
const themeInstance={
背景颜色:“卡德蓝”
}
渲染(
,
根节点
)
但我似乎无法让我的子组件应用主题:
const useStyles = makeStyles(theme => {
childComp: {
backgroundColor: theme.backgroundColor
}
})
const ChildComponent: FC = () => {
const classes = useStyles()
return (
<div className={classes.childComp}>I'm a div</div>
)
}
const useStyles=makeStyles(主题=>{
儿童公司:{
backgroundColor:theme.backgroundColor
}
})
const ChildComponent:FC=()=>{
常量类=useStyles()
返回(
我是一名跳水运动员
)
}
将被渲染为未设置样式
这似乎是某种类型的类型不匹配问题,因为当我开始处理主题
参数的类型时,浏览器在一瞬间呈现了预期的输出(
带有背景色的div:cadetblue
),但没有出现错误
非常感谢您能帮我找出我的错误所在
可以找到活生生的沙箱
这经常发生在我身上。请尝试以下操作:
const useStyles = makeStyles(theme => ({
childComp: {
backgroundColor: theme.backgroundColor
}
}));
注意()
Live sandbox:您需要键入自定义主题。默认情况下,
makeStyle
将使用具有以下签名的默认主题类型:
导出接口主题{
形状:形状;
断点:断点;
方向:方向;
混合蛋白:混合蛋白;
组件?:组件;
调色板:调色板;
阴影:阴影;
间距:间距;
过渡:过渡;
印刷术:印刷术;
zIndex:zIndex;
不稳定模式:布尔型;
}
如您所见,它没有backgroundColor
属性。您需要使用模块扩充来更新主题定义,以使typescript停止抱怨不正确的主题类型
从“@materialui/core/styles/createMuiTheme”导入{Theme}”;
从“@material ui/core/styles”导入{createMuiTheme}”;
声明模块“@material ui/styles”{
接口DefaultTheme扩展MyTheme{}
}
声明模块“@material ui/core/styles/CreateMuiteme”{
接口ThemeOptions扩展了MyTheme{}
}
导出接口MyTheme扩展了主题{
背景颜色:字符串;
}
const theme=createMuiTheme({
背景颜色:“红色”
});
出口{主题};
在您的组件中
const useStyles=makeStyles((主题)=>({
儿童公司:{
backgroundColor:theme.backgroundColor
}
}));
现场演示
@ZChu我认为正确的方法是以您的全球风格设置
调色板
,并在其他任何地方访问它。我不确定为什么不能通过默认的主题
类型访问backgroundColor
,但在最终设置调色板之前,您可以使用(主题:any)
绕过它。@ZChu啊,我注意到您确实创建了一个自定义全局主题。你应该跟着