shell
npm install classnames
例子:
javascript
import classNames from 'classnames';
// 用法1:传递多个类名
const classes = classNames('foo', 'bar', 'baz');
// 结果: 'foo bar baz'
// 用法2:传递对象,根据条件来选择添加类名
const isActive = true;
const classes = classNames('button', { 'active': isActive });
// 结果: 'button active'
// 用法3:传递数组
const additionalClasses = ['btn', 'btn-primary'];
const classes = classNames('button', additionalClasses);
// 结果: 'button btn btn-primary'
React 例子
javascript
// App.js
import React, {useState} from 'react';
import classNames from 'classnames';
import styles from './App.module.css'
// MyComponent.js
function MyComponent({isActive}) {
const buttonClasses = classNames('button', {
[styles.active]: isActive,
});
return (
<button className={buttonClasses}>Active Button</button>
);
}
function App() {
const [isActive, setIsActive] = useState(false);
const toggleActive = () => {
setIsActive(!isActive);
};
return (
<div className="App">
<h1>Example App</h1>
<MyComponent isActive={isActive}/>
<button onClick={toggleActive}>Toggle Active</button>
</div>
);
}
export default App;