在反应中设置按钮动画

问题描述 投票:0回答:1

嘿,伙计们,我有一个按钮组件在我的反应项目,所以让我显示代码。

class Button extends Component {
  constructor(props){
    super(props)
    this.state = {
      active: false,
    };
  }    

  render() {
    return (
      <button
        className={
          this.state.active
            ?  "thankyou_button_active":"thankyou_button"

        }
        onClick={() =>
          this.setState({ active: !this.state.active })
        }
      >
        Thank you!
      </button>
    );


  }
}

.css

.thankyou_button_active {
  transition: all 0.4s ease-in;
  background-color: #ff9d72;
  color: white;
  border: 1px solid #ff9d72;
  width: 120px;
  outline: none;
  height: 31px;
  font-weight: 700;
  border-radius: 30px;
  font-size: 15px;
  padding: 6px 10px;
  margin-bottom: 1rem;
  transform: translateY(4px);

}
.thankyou_button {
  border: 1px solid #ff9d72;
  background: white;
  color: #ff9d72;
  width: 120px;
  outline: none;
  height: 31px;
  font-weight: 700;
  border-radius: 30px;
  font-size: 15px;
  padding: 6px 10px;
  margin-bottom: 1rem;
}

我正在改变onClick事件中分配给按钮的类,所以最初我的按钮状态'active'是false,所以分配的类是'thankyou_button',但是第一次点击后分配的类是'thankyou_button_active'。

在这个变化的状态下,我希望我的按钮应该有一个按压的效果,比如在Y轴上向上向下走一点,然后回到原来的位置......用这个CSS按钮会向下走,就像我在'thankyou_button_active'类中提到的那样,但是不会出现,因为这个类在下一次点击之前仍然是活动的。

javascript css reactjs frontend css-transitions
1个回答
1
投票

尝试添加 setTimeout 之后 setState 为了再次翻转状态,使类在动画结束后会翻转回非活动状态(或正常类),你需要添加 transition: all 0.4s ease-in;.thankyou_button 类也是。

工作代码。

React:

class Button extends Component {
  constructor(props){
    super(props)
    this.state = {
      active: false,
    };
  }    

  render() {
    return (
      <button
        className={
          this.state.active
            ?  "thankyou_button_active":"thankyou_button"

        }
        onClick={() =>
          this.setState({ active: !this.state.active })
          setTimeout(()=>{
            this.setState({ active: !this.state.active })
           },400)
        }
      >
        Thank you!
      </button>
    );


  }
}

css:

.thankyou_button_active {
  transition: all 0.4s ease-in;
  background-color: #ff9d72;
  color: white;
  border: 1px solid #ff9d72;
  width: 120px;
  outline: none;
  height: 31px;
  font-weight: 700;
  border-radius: 30px;
  font-size: 15px;
  padding: 6px 10px;
  margin-bottom: 1rem;
  transform: translateY(4px);

}
.thankyou_button {
  transition: all 0.4s ease-in;
  border: 1px solid #ff9d72;
  background: white;
  color: #ff9d72;
  width: 120px;
  outline: none;
  height: 31px;
  font-weight: 700;
  border-radius: 30px;
  font-size: 15px;
  padding: 6px 10px;
  margin-bottom: 1rem;
}

笔。https:/codepen.iodavsugipendyYvOME?editors=0111。

© www.soinside.com 2019 - 2024. All rights reserved.