【问题标题】:React-Webpack. Update className with css-loader反应-Webpack。使用 css-loader 更新 className
【发布时间】: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}>&nbsp;</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


【解决方案1】:

您可以使用非常棒的类名包,它可以让您轻松拥有多个类。我不确定您的最终目标,但可以很容易地执行以下操作:

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

https://github.com/JedWatson/classnames

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-01
    • 2017-10-27
    • 2017-07-21
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 2023-04-01
    • 2015-12-22
    相关资源
    最近更新 更多