您可以使用将与空格联接的数组。即
<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