How to override (overwrite) classes and styles in material-ui (React)

前端 未结 2 996
忘了有多久
忘了有多久 2021-01-01 16:08

I\'m using version 1.2.1 of material-ui and I\'m trying to override the AppBar component to be transparent. The documentation outlines how to override styles here.

My

相关标签:
2条回答
  • 2021-01-01 16:25
    import React, { Component } from 'react';
    import AppBar from '@material-ui/core/AppBar';
    import Toolbar from '@material-ui/core/Toolbar';
    import logo from '../Assets/logo.svg';
    import { withStyles } from '@material-ui/core/styles';
    
    const styles = {
      transparentBar: {
        backgroundColor: 'transparent !important',
        boxShadow: 'none',
        paddingTop: '25px',
        color: '#FFFFFF'
      }
    };
    
    class NavigationBar extends Component {
      render() {
        return (
          <AppBar className={classes.transparentBar}>
            <Toolbar>
              <img src={logo} style={{ height: '28px' }} />
            </Toolbar>
          </AppBar>
        );
      }
    }
    
    export default withStyles(styles)(NavigationBar);
    

    find the important part as :

    backgroundColor: 'transparent !important'
    

    refer this guide for more details: https://material-ui.com/customization/overrides/

    hope this will help you

    0 讨论(0)
  • 2021-01-01 16:33

    This answer makes @Nadun answer complete - he deserves the credit. To override material ui classes we need to understand these things:

    1. Add your styles in a const variable at the top

        const styles = {
          root: {
            backgroundColor: 'transparent !important',
            boxShadow: 'none',
            paddingTop: '25px',
            color: '#FFFFFF'
          }
        };
    

    2. We need to use higher order function with "withStyles" to override material ui classes

        export default withStyles(styles)(NavigationBar);
    

    3. Now these styles are available to us as props in the render function try doing this - console.log(this.props.classes) - you get a classes name correspoding to properties you include in styles object, like - {root: "Instructions-root-101"}.

    Add that with classes attribute

    render() {
       const { classes } = this.props;
       return ( 
           <AppBar classes={{ root: classes.root }}>
            // Add other code here
           </AppBar>
       )
    }
    
    0 讨论(0)
提交回复
热议问题