javascript - React JS 在悬停时切换/添加类

标签 javascript reactjs events dom-events animate.css

我将 animate.css 库与 React 一起使用,并尝试设置一个元素(按钮)在鼠标悬停时发出脉冲。试图查看文档和此处,但找不到实现此简单任务的方法。如果有人实现了这一目标或找到了引用,我们将不胜感激。

class App extends Component {

   constructor(props) {
    super(props);

    this.handleHover = this.handleHover.bind(this);
  }

  handleHover(){
    this.setState({
        isHovered: !this.state.isHovered
    });
  }

  render() {
    const btnClass = this.state.isHovered ? "pulse animated" : "";

    return (
      <div>
        <button className={btnClass} onMouseEnter={this.state.handleHover} onMouseLeave={this.state.handleHover}>Test</button>
      </div>
    );
  }
}

export default App;

最佳答案

您可以在组件上使用 onMouseEnteronMouseLeave 事件并相应地切换类。

constructor(){
    super();
    this.state = {
        isHovered: false
    };
    this.handleHover = this.handleHover.bind(this);
}
handleHover(){
    this.setState(prevState => ({
        isHovered: !prevState.isHovered
    }));
}
render(){
    const btnClass = this.state.isHovered ? "pulse animated" : "";
    return <button className={btnClass} onMouseEnter={this.handleHover} onMouseLeave={this.handleHover}></button>
}

2019 年 5 月 7 日更新: Hook

import React, { useState } from 'react';

export default function Component () {
  const [hovered, setHovered] = useState(false);
  const toggleHover = () => setHovered(!hovered);
  return (
    <button 
      className={hovered ? 'pulse animated' : ''}
      onMouseEnter={toggleHover}
      onMouseLeave={toggleHover}
    >
    </button>
  )
}

关于javascript - React JS 在悬停时切换/添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44575727/

相关文章:

javascript - HTML5 Canvas 描边具有一致的 alpha 值

javascript - 无法获取配置 json 文件

reactjs - React-hook-form 'ignores' 选择

c++ - 确定场景何时在 Maya 中完成加载

javascript - 在 jQuery 中 : how to make a function update when the user expands the window

javascript - 在组件上设置所需的 Prop

javascript - 有效的reactjs组件在嵌套时不会渲染

java - JButtons 没有正确显示 borderlayout,还有向按钮添加 actionListener 的问题

jquery - 设置全日历单元格背景颜色

javascript - 带有 html 内容的 jquery ui 工具提示