class拼接方法库classnames
一个用于管理class名的js库。
npm-classnames、github-classnames
安装
1
| npm i --save-dev classnames
|
使用
1 2 3 4 5 6 7 8
| import classnames from 'classnames' let classDatas = { 'm-table': true, 'z-hide': false }; let newClass = 'f-black'
let className = classnames(classDatas, newClass);
|
1 2 3 4 5 6 7 8
| 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', 'foo', 'bar'); classNames('foo', { foo: false, bar: true });
|
可以利用这个方法来动态控制键值的true/fale变化,从而控制是否返回键。注意:默认是返回的。
bind()方法
如果是name和className进行了映射,可以使用bind方法
1 2 3 4 5 6 7 8 9 10 11
| var classNames = require('classnames/bind');
var styles = { foo: 'abc', bar: 'def', baz: 'xyz' };
var cx = classNames.bind(styles);
var className = cx('foo', ['bar'], { baz: true });
|
react中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import { Component } from 'react'; import classNames from 'classnames/bind'; import styles from './submit-button.css';
let cx = classNames.bind(styles);
export default class SubmitButton extends Component { render () { let text = this.props.store.submissionInProgress ? 'Processing...' : 'Submit'; let className = cx({ base: true, inProgress: this.props.store.submissionInProgress, error: this.props.store.errorOccurred, disabled: this.props.form.valid, }); return <button className={className}>{text}</button>; } };
|
Author
My name is Micheal Wayne and this is my blog.
I am a front-end software engineer.
Contact: michealwayne@163.com