嘿伙计们,我的 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 })
}
>
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' 类但没有出现,因为该类在下次单击之前仍然保持事件状态
最佳答案
尝试在setState
后面添加setTimeout
来再次翻转状态,这样动画结束后类会翻转回非事件状态(或普通类),
您还需要在 .thankyou_button
类中添加 transition: all 0.4s escape-in;
。
工作代码:
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;
}
关于javascript - 在 react 中设置按钮动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61404967/