前言
classnames
是一个JavaScript工具库,用于 有条件地 将不同的class类名组合在一起
用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| classNames('foo', 'bar');
classNames('foo', { bar: true });
classNames({ 'foo-bar': true });
classNames({ 'foo-bar': false });
classNames({ foo: true }, { bar: true });
classNames({ foo: true, bar: true });
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true });
classNames(null, false, 'bar', undefined, 0, { baz: null }, '');
let buttonType = 'primary'; classNames({ [`btn-${buttonType}`]: true });
export default function App() {
return ( <div className={classNames(...)}></div> ) }
|
源码解析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| const hasOwn = {}.hasOwnProperty;
export default function classNames () { let classes = '';
for (let i = 0; i < arguments.length; i++) { const arg = arguments[i]; if (arg) { classes = appendClass(classes, parseValue(arg)); } }
return classes; }
function parseValue (arg) { if (typeof arg === 'string') { return arg; } if (typeof arg !== 'object') { return ''; } if (Array.isArray(arg)) { return classNames.apply(null, arg); }
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) { return arg.toString(); }
let classes = '';
for (const key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes = appendClass(classes, key); } }
return classes; }
function appendClass (value, newClass) { if (!newClass) { return value; }
return value ? (value + ' ' + newClass) : newClass; }
|