在 css 模块类名上使用变量值

问题描述

我正在尝试在 nextjs 中使用带有 css 模块的类名中的变量,但我很难找出正确的语法。

我的变量来自 api:

const type = red

我是怎么做的:

<div className={` ${styles.background} ${styles.--type}`}></div>

我期望的结果:

<div className={` ${styles.background} ${styles.--red}`></div>

有办法吗?

解决方法

不确定您要实现的目标。

一种解决方案可能是:

const type = 'red';

<div className={`${styles.background} ${styles.type}`}></div>

但是,如果您想使用 BEM 和 -- 表示法。您可能需要切换到括号表示法。

const type = '--red';

<div className={`${styles.background} ${styles[type]}`}></div>