classnames
库是日常工作中用来操作dom中class相关的工具函数,这里我们对它进行解读
安装
npm i classnames --save
源码
function classNames() {
let classes = [];
for (let i = 0; i < arguments.length; i++ ) {
if(!arguments[i]) {
continue
}
const arg = arguments[i]
if(typeof arg === 'string' || typeof arg === 'number') {
// 直接插入
classes.push(arg)
} else if (Array.isArray(arg)) {
// 子项是数组,递归调用自己
arg.length && classes.push(classNames.call(null, arg))
} else if(typeof arg === 'object') {
// 判断是不是object, 是就进行遍历
if(arg.toString() === Object.prototype.toString()) {
for(let key in arg) {
if(arg[key]) {
classes.push(arg[key])
}
}
} else {
// 不是object, 直接转成字符串
classes.push(arg.toString())
}
}
}
return classes.join(' ')
}
使用
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'