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

妖精的绣舞 提交于 2019-11-29 19:53:46

问题


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

My code:

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';

class NavigationBar extends Component {
  render() {
    const styles = {
      root: {
        backgroundColor: 'transparent',
        boxShadow: 'none',
      },
    };

    return (
      <AppBar position={this.props.position} classes={{ root: styles.root }}>
        <Toolbar>
          <img src={logo} style={{ height: '28px' }} />
        </Toolbar>
      </AppBar>
    );
  }
}

export default NavigationBar;

But this yields no results. Am I trying to overwrite wrong? Not sure where I'm going wrong here...


回答1:


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>
   )
}



回答2:


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



来源:https://stackoverflow.com/questions/50831450/how-to-overwrite-classes-and-styles-in-material-ui-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!