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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33949469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:03:59  来源:igfitidea点击:

using css modules how do I define more than one style name

javascriptcssreactjs

提问by Navela

I am trying to use multiple classes for an element using css modules. How do I do this?

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

回答by svnm

You can add multiple classes using css modules as follows:

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

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

e.g.

例如

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

Using react-css-modulesyou can use normal class name syntax:

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

<div styleName='description yellow'>

<div styleName='description yellow'>

and you specify allowMultiple: truefor multiple classes

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

回答by Dudeonyx

You can use an array that will be joined with a space. i.e

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

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

I prefer this to using template literals like @steven isekisuggested because it is easier to add and remove classes without having to wrap them in ${}every single time.

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

But if you're for some reason adding a lot of classes to a lot of elements you can write a higher order function to make it easier

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

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'

Usage

用法

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

Looks very neat and readable.

看起来非常整洁和可读。

When rendered to the DOM it becomes

当渲染到 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) */

As expected

正如预期的那样

And it can be used with conditionals by putting the conditionally generated classes in an array that is used as an argument for classes via ... spread operator

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

In fact while answering this I decided to publish an npm module because why not.

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

Get it with

得到它

npm install css-module-class-lister

回答by f.jafari

for combine class names in front of className property, you can use "clsx", using this package is easy

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

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

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

you can find the package from this address: https://github.com/lukeed/clsx

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

回答by Yuan-Hao Chiang

I highly recommend using the classnamespackage. It's incredibly lightweight (600 bytes minified) and has no dependencies:

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

import classnames from 'classnames';

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

It even has the added benefit of being able to conditionally add class names (for example, to append a dark themeclass), without having to concatenate strings which can accidentally add an undefinedor falseclass:

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

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

回答by Riesenfaultier

Why you don't define an additional class with the multiple styles? like

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

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

and then

接着

<div class="descyellow">