【问题标题】:using css modules how do I define more than one style name使用 css 模块如何定义多个样式名称
【发布时间】:2016-03-01 04:31:40
【问题描述】:

我正在尝试使用 css 模块为一个元素使用多个类。我该怎么做?

function Footer( props) {
    const { route } = props;
    return (
        <div className={styles.footer}>
            <div className={styles.description, styles.yellow}>
              <p>this site was created by me</p>
            </div>
            <div className={styles.description}>
              <p>copyright nz</p>
            </div>
        </div>
    );
}

【问题讨论】:

标签: javascript css reactjs


【解决方案1】:

您可以使用 css 模块添加多个类,如下所示:

className={`${styles.description} ${styles.yellow}`}

例如

function Footer( props) {
    return (
        <div className={styles.footer}>
            <div className={`${styles.description} ${styles.yellow}`}>
              <p>this site was created by me</p>
            </div>
        </div>
    );
}

使用react-css-modules,您可以使用普通的类名语法:

&lt;div styleName='description yellow'&gt;

你为多个类指定allowMultiple: true

【讨论】:

  • 你可以使用 ES2015 语法。应该是${styles.class1} ${styles.class2}
  • 感谢@Golinmarq 现在更新
  • 似乎在 react-create-app 的最新版本中它不再起作用,它触发:“不允许重复道具”
  • 拜托,你能具体说一下,我们应该在哪里添加allowMultiple: true?我找不到任何相关的东西
  • @NorayrGhukasyan export default CSSModules(Footer, styles, {allowMultiple: true} ) 检查here
【解决方案2】:

为什么不定义一个具有多种样式的附加类? 喜欢

div .descyellow{
  background_color: yellow;
  style...
}

然后

<div class="descyellow">

【讨论】:

  • css 模块给了我一个很好的机会来分离 css 类,并且由于 css 加载器中的散列,它们自动是唯一的。你是对的,这个黄色类可能不是一个很好的例子,因为我想我现在会使用simple vars plugin从变量列表中传递颜色我只是想知道你怎么能做到这一点?
【解决方案3】:

您可以使用将与空格连接的数组。即

<div className={[styles.App, styles.bold, styles['d-flex-c']].join(' ')}>

我更喜欢使用 @steven iseki 建议的模板文字,因为它更容易添加和删除类,而不必每次都将它们包装在 ${} 中。

但是如果你出于某种原因向很多元素添加了很多类,你可以编写一个更高阶的函数来使它更容易

import React from 'react';
import styles from './Person.module.css';

console.log(styles);
// sample console output =>
// {
//   App: 'App_App__3TjUG',
//   'd-flex-c': 'App_d-flex-c__xpDp1',
// }


// func below returns a function that takes a list of classes as an argument
// and turns it in an array with the spread operator and reduces it into a spaced string

const classLister = styleObject => (...classList) =>
  classList.reduce((list, myClass) => {
    let output = list;
    if (styleObject[myClass]) {
      if (list) output += ' '; // appends a space if list is not empty
      output += styleObject[myClass]; 
      //Above: append 'myClass' from styleObject to the list if it is defined
    }
    return output;
 }, '');

const classes = classLister(styles); 
// this creates a function called classes that takes class names as an argument
// and returns a spaced string of matching classes found in 'styles'

用法

<div className={classes('App', 'bold', 'd-flex-c')}>

看起来非常整洁易读。

当渲染到 DOM 时,它变成了

<div class="App_App__3TjUG App_d-flex-c__xpDp1">
/* Note: the class 'bold' is automatically left out because
   in this example it is not defined in styles.module.css 
   as you can be observe in console.log(styles) */

如预期的那样

它可以与条件语句一起使用,方法是将条件生成的类放在一个数组中,该数组通过...扩展运算符用作类的参数

事实上,在回答这个问题时,我决定发布一个 npm 模块,因为为什么不呢。

用它来获取它

npm install css-module-class-lister

【讨论】:

  • 太棒了。非常感谢。
  • 为什么不像 svnm 建议的那样只使用 className={${styles.description} ${styles.yellow}} ???
  • @VladyslavGoloshchapov “因为添加和删除类更容易,而不必每次都将它们包装在 ${} 中”。
【解决方案4】:

对于在className属性前组合类名,你可以使用“clsx”, 使用这个包很容易

import clsx from 'clsx';
// Strings
clsx('foo', 'bar', 'baz'); // 'foo bar baz'

// Objects
clsx({ foo:true, bar:false, baz:true });// 'foo baz'

你可以从这个地址找到包裹: https://github.com/lukeed/clsx

【讨论】:

    【解决方案5】:

    我强烈推荐使用classnames 包。它非常轻量级(缩小了 600 字节)并且没有依赖关系:

    import classnames from 'classnames';
    
    Function footer(props) {
      ...
      <div className={classnames(styles.description, styles.yellow)}>
    }
    

    它甚至还有一个额外的好处是能够有条件地添加类名(例如,附加一个深色主题类),而不必连接可能意外添加undefinedfalse类:

      <div className={classnames(styles.description, {styles.darkTheme: props.darkTheme })}>
    

    【讨论】:

      【解决方案6】:

      您应该添加 方括号 以使 classNames 成为一个数组,并删除 ',' 添加 join()

      function Footer( props) {
          const { route } = props;
          return (
              <div className={styles.footer}>
                  <div className={ [styles.description, styles.yellow].join(' ') }>
                    <p>this site was created by me</p>
                  </div>
                  <div className={styles.description}>
                    <p>copyright nz</p>
                  </div>
              </div>
          );
      }
      

      【讨论】:

        【解决方案7】:

        作为Yuan-Hao Chianganswer 的补充,以下功能使其更易于使用:

        const classes = (classNames: Array<string> | string): string => classnames((Array.isArray(classNames) ? classNames : classNames.split(' ')).map(x => styles[x]));
        

        它的作用是获取一个数组或一个字符串(然后将其拆分为一个字符串数组),并返回一个最终类名(范围为当前模块,因为它当然使用导入的styles 对象) .

        你可以这样使用它:

        <div className={classes(['description', 'dark-theme', 'many', 'more', 'class-names'])}>
        

        或者,如果您愿意,可以指定一个字符串(在使用多个类的情况下很方便,例如使用 TailwindCSS):

        <div className={classes('description dark-theme many more class-names')}>
        

        【讨论】:

          【解决方案8】:

          安装类名包以将类名连接在一起

          npm install classnames --save
          

          解决方案:

          import cx from 'classnames';
          
          Function footer(props) {
           ...
           <div className={cx(styles.description, styles.yellow)}>
          }
          

          【讨论】:

            【解决方案9】:

            如果您正在使用 classnames 包并且想要有条件地应用样式,则需要使用带括号的动态属性键,如下所示:

            <div className={classNames(styles.formControl, { [styles.hidden]: hidden })}>
            </div>
            

            【讨论】:

              【解决方案10】:

              简单地做

              <div className={style.smallFont + " " + style.yellowColor}>
              

              字符串连接

              【讨论】:

                【解决方案11】:

                我的情况最好的解决方案是下面的函数。 因为随着参数解构,我可以返回带有空格的类。

                export function clx(...classes) {
                  return classes.join(" ");
                }
                // className={clx('border', styles.form, styles.h1, 'classe-4')}
                // class="border form_CDE h1_AB"
                

                【讨论】:

                  【解决方案12】:

                  这很快就会失控:

                   className={`${styles.description} ${styles.yellow}`}
                  

                  我喜欢创建一个设置类并调用它的函数:

                  const setClass = (classes: string[]) => {
                      return classes.map((className) => styles[className]).join(" ");
                    };
                  <article className={setClass(["student", "student-expand-view-layout"])}>
                  

                  【讨论】:

                    猜你喜欢
                    • 2013-06-09
                    • 2018-12-22
                    • 2021-04-12
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2013-02-04
                    相关资源
                    最近更新 更多