我正在尝试创建一个卡片组件。我想在单击时翻转卡片。如何添加点击时旋转卡片的动画?到目前为止我的代码:
import React, { Component } from 'react';
class FlipCard extends Component {
constructor(props) {
super(props);
this.state = {
active: true
}
}
cardClick=()=>{
const currentState = this.state.active;
this.setState({
active: !currentState
});
}
render(){
return(
<div>
<div
className={this.state.active ? 'newCard, flipMe' : 'newCard'}
onClick = {this.cardClick}
>
<div className='frontCard'> I'm Front </div>
<div className='backCard'> I'm Back </div>
</div>
</div>
)
}
}
export default FlipCard;
样式:
.newCard{
position: absolute;
width:200px; height: 200px;
transform-style: preserve-3d;
transition: all 0.5s ease
}
.flipMe{
transform: rotateY(180deg);
}
.frontCard{
position: absolute;
width:100%; height: 100%; background-color:grey;
backface-visibility: hidden
}
.backCard{
position: absolute;
width:100%; height: 100%; background-color:grey;
backface-visibility: hidden;
transform: rotateY(180deg)
}
因此,当单击卡片时,我将更改事件状态,并且希望卡片旋转并显示 backCard
div。如果我添加悬停
,它就会起作用:
.newCard:hover{
transform: rotateY(180deg);
}
但我希望它单击而不是悬停。我该怎么做?
最佳答案
为您的元素指定一个 ref 属性,并使用“this.refs”更改其类名 like this :
class FlipCard extends React.Component {
handleClick(){
this.refs.Card.classList.toggle("backCard");
this.refs.Card.classList.toggle("frontCard");
this.refs.frontCard.classList.toggle("deactive");
this.refs.frontCard.classList.toggle("active");
this.refs.backCard.classList.toggle("deactive");
this.refs.backCard.classList.toggle("active");
}
render(){
return (
<div>
<div
ref="Card"
className="frontCard"
onClick={this.handleClick.bind(this)}>
<div
ref="frontCard"
className="active">Front Card</div>
<div
ref="backCard"
className="back deactive">Back Card</div>
</div>
</div>
)
}
}
export default FlipCard
CSS:
.frontCard{
display: flex;
width: 25vw;
height: 25vw;
background-color: blue;
justify-content: center;
align-items: center;
cursor: pointer;
transition: 1s ease;
}
.backCard{
transform: rotatey(180deg);
transition: 1s ease;
display: flex;
width: 25vw;
height: 25vw;
background-color: blue;
justify-content: center;
align-items: center;
cursor: pointer;
}
.deactive{
display: none;
}
.back {
transform: rotatey(180deg);
}
.active {
display: block;
transform: rotatey();
}
关于javascript - 添加类来 react div onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57752300/