【问题标题】:Remove class after adding / Restart CSS animation onClick in React在 React 中添加/重新启动 CSS 动画 onClick 后删除类
【发布时间】:2018-01-06 17:18:36
【问题描述】:

我正在使用 CSS transform 在单击 AwesomeFont 图标时为其设置动画

.animate {
    -webkit-animation-duration: 400ms;
    -webkit-animation-name: animation
}

AFAIK,要触发动画,我需要在渲染后将上述类添加到元素中。所以我在 React 中这样做

class Class extends Component {
  state = {
    likes: 5,
    play: false
  }

  handleClick = () => {
    this.setState((p) => { return {play: p.play ? false : true}; })
  }

  render() {
    <a onClick={this.handleClick} href="#" />
      <Icon className={this.state.play ? 'animate' : ''} name="thumbs-up" />
      {this.state.likes}
    </a>
  }
}

如果我只是在每次点击时切换状态,效果会很好,但现在我想在每次点击时触发动画

...

  handleClick = () => {
    this.setState((p) => { return {play: p.play ? false : true}; })
  }

  render() {
    <a onClick={this.handleClick} onMouseUp={() => this.setState(()=>{return {play:false}; })} href="#" />
      <Icon className={this.state.play ? 'animate' : ''} name="thumbs-up" />
      {this.state.likes}
    </a>
  }
}

它不漂亮,但我只是想说明一点,我认为它没有按应有的方式工作,因为重复单击链接的数字部分不会触发动画,而是单击Icon可以。

我尝试添加类onMouseDown 并删除它onMouseUp,但React 只是批量处理setStates,结果什么也没有。有任何想法的人应该如何解决这个问题?

【问题讨论】:

    标签: javascript html css reactjs animation


    【解决方案1】:

    请尝试将标签更改为 div 标签。单击和其他鼠标事件在 div 及其子元素上工作正常。看一个例子:

    <div id='wrapper' onClick='wrapperClick()' onMouseUp='wrapperMouseUp()'>
      This is parent
      <div id='child'>
        I am child
      </div>
    </div>
    
    
    #wrapper {
      width:100px;
      height:100px;
      border:1px solid black;
    }
    
    #child {
      padding-top:10px;
      border:1px solid red;
    }
    
    function wrapperClick() {
      alert('you clicked me')
    }
    
    function wrapperMouseUp() {
      alert('Mouse Up')
    }
    

    请注意,鼠标向上在点击事件之前触发。

    handleMouseUp = () => {
      setCounter()
    }
    handleClick = () => {
      setCounter()
    }
    
    setCounter() {
      this.setState((p) => { return {play: p.play ? false : true}; })
    }
    
      render() {
        <div onClick={this.handleClick} onMouseUp={this.handleMouseUp} href="#" />
          <Icon className={this.state.play ? 'animate' : ''} name="thumbs-up" />
          {this.state.likes}
        </div>
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多