I'm using CSS transform
to animate an AwesomeFont icon when I click it
.animate {
-webkit-animation-duration: 400ms;
-webkit-animation-name: animation
}
AFAIK, to trigger the animation I need to add the above class to an element after it's being rendered. So I do this in React
class Class extends Component {
state = {
likes: 5,
play: false
}
handleClick = () => {
this.setState((p) => { return {play: p.play ? false : true}; })
}
render() {
<a onClick={this.handleClick} href="#" />
<Icon className={this.state.play ? 'animate' : ''} name="thumbs-up" />
{this.state.likes}
</a>
}
}
which works pretty well if I'm just toggling the states with each click, but now I want to trigger the animation on every click
...
handleClick = () => {
this.setState((p) => { return {play: p.play ? false : true}; })
}
render() {
<a onClick={this.handleClick} onMouseUp={() => this.setState(()=>{return {play:false}; })} href="#" />
<Icon className={this.state.play ? 'animate' : ''} name="thumbs-up" />
{this.state.likes}
</a>
}
}
It's not pretty, but I just want to illustrate a point, and I don't think it is working as it should because clicking on the number part of the link repeatedly doesn't trigger the animation but clicking the Icon
does.
I tried adding the class onMouseDown
and removing it onMouseUp
but React just batches up the setStates
, resulting in nothing. Anyone with any ideas how should I approach this problem?
Please try to change a tag to div tag. The click and other mouse events work fine on div and it's child elements. See an example:
<div id='wrapper' onClick='wrapperClick()' onMouseUp='wrapperMouseUp()'>
This is parent
<div id='child'>
I am child
</div>
</div>
#wrapper {
width:100px;
height:100px;
border:1px solid black;
}
#child {
padding-top:10px;
border:1px solid red;
}
function wrapperClick() {
alert('you clicked me')
}
function wrapperMouseUp() {
alert('Mouse Up')
}
Just note that mouse up fires before click event.
handleMouseUp = () => {
setCounter()
}
handleClick = () => {
setCounter()
}
setCounter() {
this.setState((p) => { return {play: p.play ? false : true}; })
}
render() {
<div onClick={this.handleClick} onMouseUp={this.handleMouseUp} href="#" />
<Icon className={this.state.play ? 'animate' : ''} name="thumbs-up" />
{this.state.likes}
</div>
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.