【问题标题】:Global theme with TypeScript/React/Material-UI带有 TypeScript/React/Material-UI 的全局主题
【发布时间】:2020-10-10 14:00:41
【问题描述】:

我正在关注the official tutorial 为我的应用创建全局主题。

我的根组件应该提供全局主题:

const themeInstance = {
  backgroundColor: 'cadetblue'
}

render (
    <ThemeProvider theme={themeInstance}>
      <ChildComponent />
    </ThemeProvider>,
    rootNode
) 

但我似乎无法让我的子组件应用主题:

const useStyles = makeStyles(theme => {
  childComp: {
    backgroundColor: theme.backgroundColor
  }
})

const ChildComponent: FC = () => {
  const classes = useStyles()
  return (
    <div className={classes.childComp}>I'm a div</div>
  )
}

&lt;ChildComponent /&gt; 被渲染为无样式。

这似乎是某种类型不匹配的问题,因为当我开始使用 theme 参数的类型时,浏览器已呈现预期的输出(&lt;ChildComponent /&gt; div 和 background-color: cadetblue)一瞬间比错误失败。

非常感谢任何帮助找出我哪里出错的方法。

可以在over here找到实时沙盒。


【问题讨论】:

    标签: javascript reactjs typescript material-ui


    【解决方案1】:

    您需要输入您的自定义主题。默认情况下makeStyle 将使用具有以下签名的默认主题类型:

    export interface Theme {
      shape: Shape;
      breakpoints: Breakpoints;
      direction: Direction;
      mixins: Mixins;
      components?: Components;
      palette: Palette;
      shadows: Shadows;
      spacing: Spacing;
      transitions: Transitions;
      typography: Typography;
      zIndex: ZIndex;
      unstable_strictMode?: boolean;
    }
    

    如您所见,它没有backgroundColor 属性。您需要使用 module augmentation 来更新 Theme 定义,以使 typescript 停止抱怨不正确的主题类型。

    import { Theme } from "@material-ui/core/styles/createMuiTheme";
    import { createMuiTheme } from "@material-ui/core/styles";
    
    declare module "@material-ui/styles" {
      interface DefaultTheme extends MyTheme {}
    }
    
    declare module "@material-ui/core/styles/createMuiTheme" {
      interface ThemeOptions extends MyTheme {}
    }
    
    export interface MyTheme extends Theme {
      backgroundColor: string;
    }
    
    const theme = createMuiTheme({
      backgroundColor: "red"
    });
    
    export { theme };
    

    在你的组件中

    const useStyles = makeStyles((theme) => ({
      childComp: {
        backgroundColor: theme.backgroundColor
      }
    }));
    

    现场演示

    【讨论】:

      【解决方案2】:

      这经常发生在我身上。请尝试以下操作:

      const useStyles = makeStyles(theme => ({
        childComp: {
          backgroundColor: theme.backgroundColor
        }
      }));
      

      注意( )

      实时沙盒:https://stackblitz.com/edit/react-ts-e7vw8s?file=childComponent.tsx

      【讨论】:

      • @ZChu 我相信正确的方法是以您的全局样式设置palette 并在其他任何地方访问它。我不确定为什么 backgroundColor 无法通过默认的 Theme 类型访问,但您可以通过 (theme: any) 绕过它,直到您最终设置调色板。
      • @ZChu Ahh,我注意到您确实制作了自定义全局主题。你应该关注material-ui.com/customization/theming
      猜你喜欢
      • 2019-12-24
      • 1970-01-01
      • 2021-11-14
      • 2020-01-24
      • 1970-01-01
      • 2019-05-23
      • 2019-09-14
      • 1970-01-01
      • 2015-12-26
      相关资源
      最近更新 更多