npm:https://www.npmjs.com/package/classnames
github:https://github.com/JedWatson/classnames

在ant-design的源码实现中,就大量使用了这种方式来拼接当前元素的className
例如:

  1. let alertCls = classNames(prefixCls, {
  2. [`${prefixCls}-${type}`]: true,
  3. [`${prefixCls}-close`]: !this.state.closing,
  4. [`${prefixCls}-with-description`]: !!description,
  5. [`${prefixCls}-no-icon`]: !showIcon,
  6. [`${prefixCls}-banner`]: !!banner,
  7. }, className);

使用

  1. import classNames from 'classnames';
  2. classNames('foo', 'bar'); // => 'foo bar'
  3. classNames('foo', { bar: true }); // => 'foo bar'
  4. classNames({ 'foo-bar': true }); // => 'foo-bar'
  5. classNames({ 'foo-bar': false }); // => ''
  6. classNames({ foo: true }, { bar: true }); // => 'foo bar'
  7. classNames({ foo: true, bar: true }); // => 'foo bar'
  8. // lots of arguments of various types
  9. classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
  10. // other falsy values are just ignored
  11. classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'