【问题标题】:How do I globally override variant, color, style, etc. for Material-UI components?如何全局覆盖 Material-UI 组件的变体、颜色、样式等?
【发布时间】:2018-10-21 06:29:08
【问题描述】:

而不是到处这样做:

<Button variant="contained" color="primary" 
  style={{textTransform: "none"}}    
>
  Description
</Button>

我只想写:

<Button>
  Description
</Button>

我可以使用主题覆盖来执行此操作吗?会是什么样子?

请注意,我正在尝试覆盖 Material-UI 属性和 CSS 样式。我想在全球范围内执行此操作(即不在任何地方使用 withStyles() 东西)。

或者这只能通过定义某种新的AppButton 组件来完成?

目前使用ma​​terial-ui 3.2.2

【问题讨论】:

    标签: material-ui


    【解决方案1】:

    您可以使用主题的全局覆盖来做到这一点。 文档在这里https://material-ui.com/customization/themes/#customizing-all-instances-of-a-component-type

    这样做仍然允许您在每个组件的基础上覆盖变体。

    const theme = createMuiTheme({
      props: {
        // Name of the component ⚛️
        MuiButton: {
          // The properties to apply
          variant: 'contained'
        },
      },
    });
    

    【讨论】:

      【解决方案2】:

      这是另一种方法,无需定义新组件。

      当与 Material-UI 的 JSS 样式解决方案和 Typescript 一起使用时,自定义组件可能会很尴尬。当组合来自共享组件的样式类型和使用它的事物时,我发现很难定义 WithStyle 类型。

      除了定义组件之外,还可以定义一组默认属性,然后使用扩展运算符应用这些属性。

      在应用中的某处定义并导出一组标准的共享道具:

      import {LinearProgressProps} from "@material-ui/core/LinearProgress";
      
      export const linearProps: LinearProgressProps = {
        variant:"indeterminate",
        color:"primary",
        style:{height:"2px"},
      };
      

      然后在您的应用中使用这些道具:

      <LinearProgress {...linearProps} />
      

      这很容易被自定义属性、自定义内联样式或 JSS 生成的样式覆盖:

      <LinearProgress {...linearProps} className={classes.customProgress}
        color="secondary" style={{...linearProps.style, width: "100%"}} />
      

      【讨论】:

        【解决方案3】:

        对于任何发现此问题的人,假设没有 Material-UI 方法可以做到这一点,这是我的自定义按钮组件。

        import * as React from "react";
        import {Button} from "@material-ui/core";
        import {ButtonProps} from "@material-ui/core/Button";
        
        
        export class AppButton extends React.Component<ButtonProps, {}>{
          render(){
            let {style, ...props} = this.props;
            return <Button {...props} variant="contained" color="primary"
              style={{...style, textTransform: "none"}}
            >
              {this.props.children}
            </Button>
          }
        }
        AppButton.muiName = 'Button';
        

        【讨论】:

          猜你喜欢
          • 2019-05-21
          • 2020-04-13
          • 2019-05-23
          • 2021-09-15
          • 1970-01-01
          • 2020-01-30
          • 2019-03-07
          • 2019-10-02
          • 1970-01-01
          相关资源
          最近更新 更多