【问题标题】:animate card rotating on button click in react动画卡片旋转按钮点击反应
【发布时间】:2021-01-29 22:48:40
【问题描述】:

我有 React 组件 Card,它有一个父 div,里面有两个 div(卡的正面和背面)和父 div 下方的一个按钮。我想要的是在单击按钮时旋转它们。我通过悬停和转换来做到这一点,但我很难在按钮点击时完成这项工作。

基本上,它应该在每次点击时将它们旋转 180 度。有什么想法吗?

代码结构:

function Card(){
return(
<>
 <div className="parent">
    <div className="front-side"> 

    <div/>
    <div className="back-side"> 

    <div/>
 </div>
 <button onClick={ }>Rotate</button>
</>
)

}

谢谢!

编辑:

css:

.front,.back{
    border: 1px solid black;
    width: 300px;
    height: 440px;
    overflow: hidden;
    backface-visibility: hidden;
    position: absolute;
    transition: transform .6s linear;
  }
.front {
    background: whitesmoke;
    transform: perspective(600px) rotateY(0deg);
}
.back{
    background: skyblue;
     transform: perspective(600px) rotateY(-180deg); 
}

.card:hover > .front{
    transform: perspective(600px) rotateY(180deg);
  }
.card:hover > .back{ 
    transform: perspective(600px) rotateY(0deg);
  }  

【问题讨论】:

  • 能否提供css代码,您是如何通过悬停实现这一点的?
  • 是的,我会在编辑中添加它。

标签: css reactjs transform


【解决方案1】:

使用本地状态保存旋转状态,并使用类而不是伪类简单地重写你的 css。

function Card(){
  const [isRotated, setIsRotated] = React.useState(false);

  const onRotate = () => setIsRotated((rotated) => !rotated);
  return(
    <div className={`card ${isRotated ? 'rotated' : ''}`} onClick={onRotate}>
      <div className="front"> 

  </div>
  <div className="back"> 

  </div>
</div>

); }

然后像这样改变你的css:

.card.rotated > .front{
transform: perspective(600px) rotateY(180deg);

}

.card.rotated > .back{ 
    transform: perspective(600px) rotateY(0deg);
  }  

我在 codepen 上创建了一个示例,请查看 - https://codepen.io/fadetoblack1/pen/zYoxNXx

【讨论】:

  • 我设法让它与关键帧动画一起使用,但这看起来更清晰,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 2017-05-18
  • 2022-07-20
相关资源
最近更新 更多