[英]Adding class to react div onClick
我正在嘗試創建卡組件。 我想翻轉卡片onClick。 如何添加動畫以旋轉卡片onClick? 到目前為止,我的代碼:
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。 如果我添加hover
,它可以工作:
.newCard:hover{
transform: rotateY(180deg);
}
但我希望它onClick而不是懸停。 我該怎么做呢?
給您的元素一個ref屬性,並使用“ this.refs”更改其類名, 如下所示 :
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.