使用 css 模块如何定义多个样式名称

新手上路,请多包涵

我正在尝试使用 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>
    );
}

原文由 Navela 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 732
2 个回答

您可以使用 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 你可以使用普通的类名语法:

<div styleName='description yellow'>

并且您为多个类指定 allowMultiple: true

原文由 svnm 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

 <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

原文由 Dudeonyx 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏