无法在React.js中为按钮切换类

时间:2016-10-29 13:38:35

标签: javascript html css reactjs css-transitions

我希望使用类切换为button创建移动动画,就像在this example中一样。由于某些原因,我的代码被破坏了:它调用了click处理程序,但不会影响类。

代码(我使用React,Classnames和Webpack):

index.jsx:

import React from "react";
import styles from "./index.css";
import classnames from "classnames";

export default class PlaylistButton extends React.Component {
  onClick() {
    alert("clicked");
    $('.transform').toggleClass('transform-active');
  }

  render() {
    return (
        <button className = {classnames(styles.button, styles.transform)} onClick = {() => this.onClick()}>label</button>
    );
  }
}

index.css:

.button {
  font-size: 30px;
  color: white;
  background-color: #5266ed;
  margin-bottom: 5px;
  border: none;
  width: 300px;
  height: 75px;
}

.transform {
  -webkit-transition: all 2s ease;
  -moz-transition: all 2s ease;
  -o-transition: all 2s ease;
  -ms-transition: all 2s ease;
  transition: all 2s ease;
}

.transform-active {
  margin-left: -200px;
}

错误是什么?

1 个答案:

答案 0 :(得分:1)

css-modules将在运行时用随机字符串替换您的类名。因此,styles.transform的预期类名称不会是transform,因为它将替换为随机字符串。要回答您的问题,您需要在jquery中使用styles.transformstyles.transform-active

onClick() {
    alert("clicked");
    $('.'+ styles.transform ).toggleClass(styles.transform-active);
  }

css-modules会将您的类名转换为以下内容。

enter image description here

希望这有帮助!