1

据我了解,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}>&nbsp;</a>
      </div>
    )
  }
}

它实际上做了什么,它使 2 条线在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);
  }
}
4

1 回答 1

1

您可以使用非常棒的类名包,它可以让您轻松拥有多个类。我不确定你的最终目标,但这样做很容易:

<a className={classNames(
    styles.closeCross, { // <-- always applied
        [styles.closeLine]: this.state.close   <-- applied only when closed
    })}
>&nbsp;</a>

https://github.com/JedWatson/classnames

于 2017-03-02T02:51:18.330 回答