跳到主要内容

React 插件

classnames

用于有条件地将类名连接在一起,可以更简洁的绑定多个 className

npm install classnames

用法:

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'

classNames({ [`btn-${key}`]: true }); // key = 1, => 'btn-1'

示例:

import { useState } from 'react';
import classNames from 'classnames';

function App() {
const [count, setCount] = useState(0);

const btnClass = classNames({
btn: count > 1
});

const key = 1;
const bc = classNames({ [`btn-${key}`]: true });

const handleClick = () => {
setCount(count + 1);
};
return (
<>
<h1 className={btnClass}>{count}</h1>
<button onClick={handleClick}>click</button>
</>
);
}

export default App;

使用 CSS Modules 的示例:

import { useState } from 'react';
import classNames from 'classnames/bind';
import styles from './index.module.less';

const cx = classNames.bind(styles);

function App() {
const [count, setCount] = useState(0);

const btnClass = cx({
btn: count > 1
});

const handleClick = () => {
setCount(count + 1);
};
return (
<>
<h1 className={btnClass}>{count}</h1>
<button onClick={handleClick}>click</button>
</>
);
}

export default App;