複数classNameの適用
classnamesをインストール(react-starter-kitにはインストール済み)
yarn add classnames --save
classnamesをインポート
import ClassNames from 'classnames';
true,falseで適用するclassNameを決定
const classNames = ClassNames({
[s.button]: true,
[s.buttonColor]: this.state.isBlue,
[s.buttonSize]: this.state.isBig,
});
ボタン押下で適用クラスが切り替えられるサンプル
Home.js
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import ClassNames from 'classnames';
import s from './Home.css';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
isBlue: true,
isBig: true,
};
}
colorChange = () => {
this.setState({ isBlue: !this.state.isBlue });
};
sizeChange = () => {
this.setState({ isBig: !this.state.isBig });
};
render() {
const classNames = ClassNames({
[s.button]: true,
[s.buttonColor]: this.state.isBlue,
[s.buttonSize]: this.state.isBig,
});
return (
<div className={s.root}>
<input
type={'button'}
className={classNames}
value={this.state.isBlue ? 'none' : 'blue'}
onClick={() => this.colorChange()}
/>
<input
type={'button'}
className={classNames}
value={this.state.isBig ? 'small' : 'big'}
onClick={() => this.sizeChange()}
/>
</div>
);
}
}
export default withStyles(s)(Home);
Home.css
.root {
padding-left: 20px;
padding-right: 20px;
}
.button {
height: 30px;
width: 60px;
}
.buttonColor {
background: #6688ff;
}
.buttonSize {
height: 60px;
width: 80px;
}