# classnames

npm install classnames --save
yarn add classnames

# 用法

import clx from 'classnames';

基本用法:

  • classnames构造函数接受任意个参数,可以是字符串、对象或者数组
  • foo{foo:truthy}的简写形式,当是假值时就不会使用foo
  • 数组会被递归扁平化
# 字符串
clx('foo','bar');  => 'foo bar'

# 对象
clx({foo: true, bar: true}); => 'foo true'

# 字符串和对象
clx('foo',{bar: true, duck: false},'baz',{quux: true}); => 'foo bar baz quux'

# 数组 ==>扁平化
clx('a', ['b', {c: true, d:false}]); => 'a b c'

可以使用计算值:

let buttonType = 'primary';
classNames({ [`btn-${buttonType}`]: true });  =>'btn-primary'

bind模式:

import classnames from 'classnames/bind';

let styles = {
    foo: 'abc',
    bar: 'def',
    baz: 'xyz'
}

let clx = classnames.bind(styles);

clx('foo', ['bar'], {baz: true}) => 'abc def xyz'

React中实际使用bind模式:

import classnames from 'classnames/bind';
import styles from './button.module.scss';

let cx = classnames.bind(styles); // 绑定

const ButtonCom = (props) => {
    let className = cx('foo', ['bar'], {baz:true});
    return (
        <button className={className}>{test}</button>
    )
}
作者:王龙楷; 标签:原创; 提交时间: 3/31/2021, 1:08:55 PM