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

Nav*_*ela 22 javascript css reactjs

我试图使用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>
    );
}
Run Code Online (Sandbox Code Playgroud)

svn*_*vnm 38

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

className={`${styles.description} ${styles.yellow}`}
Run Code Online (Sandbox Code Playgroud)

例如

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

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

<div styleName='description yellow'>

并指定allowMultiple: true多个类

  • 请问您能具体说一下,我们应该在哪里添加“allowMultiple: true”吗?我找不到任何与之相关的内容 (3认同)

Yua*_*ang 14

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

import classnames from 'classnames';

Function footer(props) {
  ...
  <div className={classnames(styles.description, styles.yellow)}>
}
Run Code Online (Sandbox Code Playgroud)

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

  <div className={classnames(styles.description, {styles.darkTheme: props.darkTheme })}>
Run Code Online (Sandbox Code Playgroud)


小智 12

您应该添加方括号以使 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>
    );
}
Run Code Online (Sandbox Code Playgroud)


Dud*_*nyx 9

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

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

我更喜欢使用类似@ 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'
Run Code Online (Sandbox Code Playgroud)

用法

<div className={classes('App', 'bold', 'd-flex-c')}>
Run Code Online (Sandbox Code Playgroud)

看起来非常整洁易读。

呈现给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) */
Run Code Online (Sandbox Code Playgroud)

符合预期

通过将有条件生成的类放在数组中,可以将其与条件条件一起使用,该数组通过...传播运算符用作类的参数

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

用它

npm install css-module-class-lister
Run Code Online (Sandbox Code Playgroud)


Dev*_*ush 5

您可以使用带有空格(' ')的字符串连接 ->

import classes from '../path/to/fileName.module.css'
<div className={classes.centerFlexY + ' ' + classes.searchTabs} />
Run Code Online (Sandbox Code Playgroud)

className 只是我们传递的一个 prop,并且这个 prop 需要一个字符串值,因此我们可以使用在 className 的 {} 块内生成字符串的每一个代码:

<div className={`${classes.imported} normalCssClass ${classes.another}`}
Run Code Online (Sandbox Code Playgroud)