【问题标题】:React JS toggle/ adding a class on hoverReact JS切换/在悬停时添加一个类
【发布时间】:2017-11-18 10:23:36
【问题描述】:

我正在使用带有 React 的 animate.css 库,并尝试设置一个元素(按钮)以在悬停时发出脉冲。试图通过文档和这里查看,但找不到完成这个简单任务的方法。如果有人实现了这一点或找到了参考,将不胜感激。

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;

【问题讨论】:

    标签: javascript reactjs events dom-events animate.css


    【解决方案1】:

    您可以在组件上使用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 日更新:挂钩

    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>
      )
    }
    

    【讨论】:

    • 当我将鼠标悬停在TypeError: Cannot read property 'setState' of null 上时收到一条错误消息特别是这一行 &gt; 34 | this.setState({
    • 是的,您需要将该函数绑定到您的组件check out the docs for more info。但基本上你可以在构造函数中做this.handleHover = this.handleHover.bind(this),或者将props更改为onMouseEnter={this.handleHover.bind(this)}onMouseLeave={this.handleHover.bind(this)}
    • 我对您的项目做了一个假设,因为您没有发布任何示例代码。如果您发布整个组件,它会更容易提供帮助。
    • 抱歉,我已经向构造函数添加了一个状态,但似乎仍然无法修复它,我将代码添加到我原来的问题中。
    • @tonejac 将函数作为第一个参数提供给this.setState时作为参数传入:reactjs.org/docs/react-component.html#setstate
    【解决方案2】:

    使用 css :hover 属性怎么样?通过将 css 文件中的悬停类部分更改为使用 :hover 而不是反应,这对我来说效果更好。

    我尝试使用上述建议,但反应似乎不够快,无法获得它,因此如果鼠标在按钮上缓慢移动,状态将变为错误。

    【讨论】:

    • 我觉得这个答案更简单高效
    • 原因是我需要修改组件ClassList或任何属性,简单地说,css是有限的。我本可以朝那个方向发展,但这需要一个新的计划。但是是的,我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    相关资源
    最近更新 更多