我之前在antd的里面看到一种做法,就是通过一个函数获取公共前缀。
感觉这种方法很好,所以自己也写了一个类似的提取公共前缀的工具函数
export const setCommonCls = (...wrapperPrefix: string[]) => {
return (className) =>
wrapperPrefix
.concat(className)
.reduce((prefix, curPrefix) => `${prefix}-${curPrefix}`);
};
我会想到这个的原因是在写react组件的时候,要区分通用组件和页面组件的类名,当然如果用了css module
的话,这种做法可能没有太大的意义。
在react通用组件内
假如定义一个通用的前缀就可以用
const prefix = "prefix";
const getCls = setCommonCls("comp", prefix);
console.log(getCls("demo")); // 'comp-prefix-demo'
意义在于我们后面改动类名前缀时可以统一管理,进行修改
启发是看到antd里有这样一个函数
getPrefixCls: (suffixCls?: string, customizePrefixCls?: string) => {
if (customizePrefixCls) return customizePrefixCls;
return suffixCls ? `${getGlobalPrefixCls()}-${suffixCls}` : getGlobalPrefixCls();
}