【问题标题】:display effect on an element on button click in react在按钮点击元素上显示效果
【发布时间】:2021-12-31 15:40:42
【问题描述】:

我正在尝试使用 2 个按钮(递增和递减)实现一个简单的计数器。 我想要实现的是,每当单击增量按钮时,计数器的值(显示为 h3)应增加 1,并且 h3 应具有文本阴影动画并将颜色更改为绿色。同样,当我单击减量时,它应该有动画并将颜色变为红色。

我面临的问题是,当我在单击增量按钮后单击减量按钮时,一切正常,反之亦然。但是当我两次单击同一个按钮时,我无法看到动画。如何做到这一点?

这是我的代码:


function App() {

  const [value, setValue] = useState(0)

  const [btnclass, setBtnClass]=useState("")
  const valueRef= useRef(0)
  const decrement=()=>{
    setBtnClass("minus")
    setValue(value-1)
  }

  const increment=()=>{
    setBtnClass("plus")
    setValue(value+1)
  }

  return (
          <div className="App">
            <div className='row'>
              <button className="btn" style={{backgroundColor:'red'}} onClick={decrement}>Decrement</button>
              <h3 ref={valueRef} className={btnclass} style={{color: `${btnclass=="minus"? "red": "green"}`}}>{value}</h3>
              <button className="btn" onClick={increment} >Increment</button>
            </div>
          </div>
  );
}

CSS 代码:


.btn {
  border: none;
  background-color: #04aa6d;
  opacity: 0.7;
  height: 100%;
  font-size: x-large;
  padding: 5px;
}

h3 {
  font-weight: bold;
  height: 100%;
  font-size: xx-large;
}

.minus {
  animation-name: minus;
  animation-duration: 0.5s;
}

@keyframes minus {
  from {
    text-shadow: none;
  }
  to {
    text-shadow: 2px 2px red;
    color: red;
  }
}

.plus {
  animation-name: plus;
  animation-duration: 0.5s;
}

@keyframes plus {
  from {
    text-shadow: none;
  }
  to {
    text-shadow: 2px 2px green;
    color: green;
  }
}

.btn:hover {
  opacity: 1;
  animation-name: button;
  animation-duration: 1s;
}

@keyframes button {
  from {
    background-color: aqua;
    transform: rotateX(0deg);
  }

  to {
    background-color: pink;
    transform: rotateX(30deg);
  }
}

我认为发生了什么-因为单击同一个按钮两次,btnclass 的值没有改变,因此动画没有显示?我对么?如果不是,请告诉我正确的方法。

【问题讨论】:

    标签: javascript html css reactjs react-hooks


    【解决方案1】:

    在 SO 上进行一些搜索后,我找到了解决方案。有一个名为onAnimationEnd 的事件。这样的编辑符合我的目的:

    <h3 className={btnclass} onAnimationEnd={()=>setBtnClass("")} style={{color: `${btnclass=="minus"? "red": "green"}`}}>{value}</h3>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      相关资源
      最近更新 更多