【问题标题】:Cannot toggle class for button in React.js无法在 React.js 中切换按钮的类
【发布时间】:2017-03-12 04:56:22
【问题描述】:

我想使用类切换为button 制作运动动画,就像在this example 中一样。由于某些原因,我的代码被破坏了:它调用了点击处理程序,但不影响类。

代码如下(我使用 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;
}

错在哪里?

【问题讨论】:

    标签: javascript html css reactjs css-transitions


    【解决方案1】:

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

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

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

    希望这会有所帮助!

    【讨论】:

    • 还是不行。也许toggleClass 参数也需要替换?
    • @JustLogin 更新了答案。
    猜你喜欢
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多