How to add multiple classes in Material UI using t

2020-05-16 13:30发布

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 => ({
 container: {
  display: 'flex',
  flexWrap: 'wrap'
},
 spacious: {
  padding: 10
},
});

Here is how I used it:

    return (
     <div className={ this.props.classes.container }>

The above works, but is there a way to add both classes, without using the classNames npm package? Something like:

     <div className={ this.props.classes.container + this.props.classes.spacious}>

11条回答
劫难
2楼-- · 2020-05-16 13:35

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'
查看更多
Emotional °昔
3楼-- · 2020-05-16 13:38

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

查看更多
Root(大扎)
4楼-- · 2020-05-16 13:45

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

查看更多
趁早两清
5楼-- · 2020-05-16 13:47

I think this will solve your problem:

const styles = theme => ({
 container: {
  display: 'flex',
  flexWrap: 'wrap'
},
 spacious: {
  padding: 10
},
});

and in react component:

<div className={`${classes.container} ${classes.spacious}`}>
查看更多
Anthone
6楼-- · 2020-05-16 13:48

If you want to assign multiple class names to your element, you can use arrays.

So in your code above, if this.props.classes resolves to something like ['container', 'spacious'], i.e. if

this.props.classes = ['container', 'spacious'];

you can simply assign it to div as

<div className = { this.props.classes.join(' ') }></div>

and result will be

<div class='container spacious'></div>
查看更多
放荡不羁爱自由
7楼-- · 2020-05-16 13:48

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

查看更多
登录 后发表回答