【发布时间】:2017-07-21 08:02:51
【问题描述】:
据我所知,即使它由许多组成,也可以通过 className={styles.className} 向元素添加一个类。
因此,目前代码使用ternary operator 来根据state.cross 值呈现不同的元素样式。
export default class Header extends Component {
constructor(props) {
super(props);
this.state = { cross: false };
this.showCross = this.showCross.bind(this);
this.showLine = this.showLine.bind(this);
}
showCross() {
this.setState({cross: true});
}
showLine() {
this.setState({cross: false});
}
render() {
return (
<div onMouseEnter={this.showCross} onMouseLeave={this.showLine} className={styles.blockClose}>
<a className={this.state.close ? styles.closeCross : styles.closeLine}> </a>
</div>
)
}
}
在更改state 并应用transform 后,它实际上使两行看起来像一个十字。
:local(.closeLine) {
...20px line
&::before {
...equal line
}
}
:local(.closeCross) {
composes: closeLine;
transform: rotate(-45deg);
&::before {
transform: rotate(90deg);
}
}
我的问题是:
是否可以通过像element.classList.toggle(className) 这样的操作来切换类来管理元素的样式,而不是条件渲染。
:local(.closeCross) {
transform: rotate(-45deg);
&::before {
transform: rotate(90deg);
}
}
【问题讨论】:
-
您可以直接在您的点击处理程序或 componentDidMount 中执行
element.classList.toggle(className),但是您将失去 Reacts 声明式编程模型的好处,因此需要从 React 控制。 -
@riscarrott,所以从你的角度来看,最好保持现状?
标签: reactjs webpack webpack-2 css-loader