reactjs 更简单/更干净的方式来应用CSS模块类?

pcww981p  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(107)

React中的常规类命名约定(或样式化组件):
className="this-class global-class"
vs CSS模块中的类命名:
className={${styles.thisClass} global-class}
第二个写起来比较麻烦
我尝试过使用 prop ,可能会使用它们,但是有没有一种更干净的方法来编写类名而不使用单独的 prop ?例如,我可以使用像classProps="this-class"这样的东西,然后让组件或某种函数将其转换为className={styles[props.classProps]}或其他东西,但这看起来像是一种复杂的方法或编写类。

ssgvzors

ssgvzors1#

将此函数添加到单独的文件夹中,并在需要对类进行逻辑操作时调用它。您需要使用npm或yarn安装clsx

npm i clsx

然后

import { ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";

export const cn = (...inputs: ClassValue[]) => {
  return twMerge(clsx(inputs))
}

所以如果你需要添加更多的类

const newClasses = ' text-white bg-black font-bold ';
<div className = {cn('publicClasses', newClasses)}> both classes will be added</div>

相关问题