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