【问题标题】:How to add multiple classes in Material UI using the classes props?如何使用 classes 道具在 Material UI 中添加多个类?
【发布时间】:2018-02-14 10:34:10
【问题描述】:

使用css-in-js方法给一个react组件添加类,如何添加多个组件?

这是类变量:

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

这是我的使用方法:

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

上述方法有效,但有没有办法在不使用classNames npm 包的情况下添加这两个类?比如:

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

【问题讨论】:

  • 也许我遗漏了一些东西,但你不能这样做
    为什么需要将它作为属性传递?
  • 你只是在两个类名之间缺少一个空格。
  • 是的,如上所述,您只需将类正确连接在一起,中间有一个空格!不需要任何额外的包。

标签: css reactjs material-design material-ui jss


【解决方案1】:

你可以使用字符串插值:

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

【讨论】:

  • 并记住不要在类之间添加逗号!我弄错了,第一个无声无息地坏了一会儿,没有注意到
  • 并且类之间必须有空格
  • 这是我第一次遇到字符串插值实际上比用老式方法编写更乏味的场景:className={classes.container+' '+classes.spacious}
  • @TJBlackman 确实,你的版本更具可读性
  • 甚至&lt;div className={[classes.container, classes.spacious].join(' ')}&gt;
【解决方案2】:

您可以使用clsx。我注意到它用于MUI buttons examples

首先安装它:

npm install --save clsx

然后将其导入到你的组件文件中:

import clsx from 'clsx';

然后在你的组件中使用导入的函数:

&lt;div className={ clsx(classes.container, classes.spacious)}&gt;

【讨论】:

  • clsx 包小于classnames,所以我更喜欢这个方案
  • clsx 包含在 Material UI 中,因此它比类名更受欢迎
  • Per Wayne Bloss 在 Mini 不太理想的答案下方的评论:@material-ui/core now depends on clsx, so if you don't want to increase your bundle size you'll want to use that instead。所以,+1 这个答案。
  • 似乎clsx 没有包含在最新的@mui/* 包中
【解决方案3】:

你可以安装这个包

https://github.com/JedWatson/classnames

然后像这样使用它

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

【讨论】:

  • 这是 Material-UI 在他们的一些示例中使用的方法,效果很好,所以我推荐这个。
  • 这应该是公认的答案。按预期工作
  • 也一直在使用这种方法。不仅对拥有多个类名很有用,而且对使其有条件也很有用。
  • @material-ui/core 现在依赖于clsx,所以如果你不想增加你的包大小,你可以使用它——npmjs.com/package/clsx
【解决方案4】:

要将多个类应用于一个组件,请将要应用的类包装在类名中。

例如,在您的情况下,您的代码应该如下所示,

import classNames from 'classnames';

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

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

确保你导入了类名!!!

看看material ui documentation,他们在一个组件中使用多个类来创建自定义按钮

【讨论】:

    【解决方案5】:

    你也可以使用extend属性(jss-extend plugin默认开启):

    const styles = theme => ({
      container: {
        display: 'flex',
        flexWrap: 'wrap'
      },
      spaciousContainer: {
        extend: 'container',
        padding: 10
      },
    });
    
    // ...
    <div className={ this.props.classes.spaciousContainer }>
    

    【讨论】:

    • 很遗憾,默认情况下不再启用...投票启用here
    【解决方案6】:

    我认为这会解决你的问题:

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

    在反应组件中:

    <div className={`${classes.container} ${classes.spacious}`}>
    

    【讨论】:

      【解决方案7】:

      这种方式可以同时添加多个字符串类和变量类或props类

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

      三节课

      【讨论】:

        【解决方案8】:

        是的,jss-composes 为您提供:

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

        然后你只需使用 classes.spacious。

        【讨论】:

        【解决方案9】:

        classNames package 也可以用作高级:

        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'
        

        【讨论】:

        • 显示错误 webpack build : Module not found: Error: Can't resolve 'classnames' in
        【解决方案10】:

        您可以在下面使用此方法:

        import clsx from 'clsx';
            
        return <div className={clsx(classes.container, 'spacious')} />
        

        这个link 有帮助。

        【讨论】:

          【解决方案11】:

          解构可以轻松完成,毕竟这些是 JavaScript 对象:

          const truncate = {
            width: '100px',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
          };
          email: {
              color: '#747474',
              ...truncate,
            },
          

          【讨论】:

            【解决方案12】:

            如果您希望为您的元素分配多个类名称,您可以使用数组

            所以在上面的代码中,如果 this.props.classes 解析为 ['container', 'spacious'] 之类的东西,即如果

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

            你可以简单地将它分配给 div

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

            结果是

            <div class='container spacious'></div>
            

            【讨论】:

            • 你确定类在结果中被,分隔
            • 不知道为什么这是公认的答案,@Glauber Ramos 是对的,Material UI 不能那样工作。
            【解决方案13】:

            如前所述,您可以使用字符串插值

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

            你可以试试classnames库, https://www.npmjs.com/package/classnames

            【讨论】:

            • 您的答案的两个部分都是由其他成员早些时候提供的。您所做的只是在一个答案中重复它们。 -1 (建议你删除这个答案并恢复你的2pts)
            猜你喜欢
            相关资源
            最近更新 更多
            热门标签