Zha*_* Yi 0 javascript css css3 reactjs
我有以下reactjs
代码.它渲染图像dom.我想实现一个羽毛,当用户点击该图像时,图像旋转180度.在旋转动画结束时,将其替换为新图像.我怎样才能在reactjs中实现它?
<div>
<img className="icon-arrow" src={icon} role="button" onClick={()=> { // create an animation to rotate the image }} />
</div>
Run Code Online (Sandbox Code Playgroud)
这是做到这一点的反应方式.
class Image extends React.Component {
constructor(props) {
super(props);
this.state = {
rotate: false,
toggle: false
};
this.rotatingDone = this.rotatingDone.bind(this);
}
componentDidMount() {
const elm = this.image;
elm.addEventListener("animationend", this.rotatingDone);
}
componentWillUnmount() {
const elm = this.image;
elm.removeEventListener("animationend", this.rotatingDone);
}
rotatingDone() {
this.setState(function(state) {
return {
toggle: !state.toggle,
rotate: false
};
});
}
render() {
const { rotate, toggle } = this.state;
return (
<img
src={
toggle
? "https://video-react.js.org/assets/logo.png"
: "https://www.shareicon.net/data/128x128/2016/08/01/640324_logo_512x512.png"
}
ref={elm => {
this.image = elm;
}}
onClick={() => this.setState({ rotate: true })}
className={rotate ? "rotate" : ""}
/>
);
}
}
ReactDOM.render(<Image />, document.getElementById("container"));
Run Code Online (Sandbox Code Playgroud)
.rotate {
animation: rotate-keyframes 1s;
}
@keyframes rotate-keyframes {
from {
transform: rotate(0deg);
}
to {
transform: rotate(180deg);
}
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
</div>
Run Code Online (Sandbox Code Playgroud)