How to add multiple classes in Material UI using the classes props

后端 未结 11 1961
花落未央
花落未央 2020-12-23 15:39

Using the css-in-js method to add classes to a react component, how do I add multiple components?

Here is the classes variable:

const styles = theme          


        
相关标签:
11条回答
  • 2020-12-23 16:26

    You can add multiple string classes and variable classes or props classes at same time in this way

    className={`${classes.myClass}  ${this.props.classes.myClass2} MyStringClass`}
    

    three classes at same time

    0 讨论(0)
  • 2020-12-23 16:28

    you can use string interpolation:

    <div className={`${this.props.classes.container} ${this.props.classes.spacious}`}>
    
    0 讨论(0)
  • 2020-12-23 16:28

    You could use clsx. I noticed it used in the MUI buttons examples

    First install it:

    npm install --save clsx

    Then import it in your component file:

    import clsx from 'clsx';

    Then use the imported function in your component:

    <div className={ clsx(classes.container, classes.spacious)}>

    0 讨论(0)
  • 2020-12-23 16:33

    As already mentioned, you can use string interpolation

    className={`${this.props.classes.container}  ${this.props.classes.spacious}`}
    

    And you can try classnames library, https://www.npmjs.com/package/classnames

    0 讨论(0)
  • 2020-12-23 16:34

    classNames package can also be used as advanced as:

    import classNames from 'classnames';
    
    var arr = ['b', { c: true, d: false }];
    classNames('a', arr); // => 'a b c'
    
    let buttonType = 'primary';
    classNames({ [`btn-${buttonType}`]: true }); // => 'btn-primary'
    
    0 讨论(0)
提交回复
热议问题