- React Cookbook
- Carlos Santana Roldan
- 289字
- 2021-07-16 17:49:40
Basic animation – implementing componentWillUpdate
In this example, we are going to learn how to use componentWillUpdate:
- componentWillUpdate allows you to manipulate a component just before it receives new props or a new state. It is typically used for animations. Let's create a basic animation (fade in/fade out) to see how to use it:
import React, { Component } from 'react';
import './Animation.css';
class Animation extends Component {
constructor() {
super();
this.state = {
show: false
};
}
componentWillUpdate(newProps, newState) {
if (!newState.show) {
document.getElementById('fade').style = 'opacity: 1;';
} else {
document.getElementById('fade').style = 'opacity: 0;';
}
}
toggleCollapse = () => {
this.setState({
show: !this.state.show
});
}
render() {
return (
<div className="Animation">
<button onClick={this.toggleCollapse}>
{this.state.show ? 'Collapse' : 'Expand'}
</button>
<div
id="fade"
className={
this.state.show ? 'transition show' : 'transition'
}
>
This text will disappear
</div>
</div>
);
}
}
export default Animation;
File: src/components/Animation/Animation.js
- As you can see, we are validating the show state with newState and observe that it is true. Then we add opacity 0, and if it is false, we add opacity 1. An important thing I want to mention about componentWillUpdate is that you can't update the state (which means you are not able to use this.setState) in this method because it will cause another call to the same method, creating an infinite loop. Let's add some styles:
.Animation {
background: red;
}
.Animation .transition {
transition: all 3s ease 0s;
color: white;
padding-bottom: 10px;
}
.Animation .transition.show {
padding-bottom: 300px;
background: red;
}
File: src/components/Animation/Animation.css
- If you run the application, you will see this view:

- After you click on the button, you will see an animation with the text fading out, and the red div will be expanded, giving you this result:

推薦閱讀
- 連接未來:從古登堡到谷歌的網(wǎng)絡(luò)革命
- Building Django 2.0 Web Applications
- SEO 20日
- JBoss EAP6 High Availability
- Proxmox High Availability
- PLC、現(xiàn)場(chǎng)總線及工業(yè)網(wǎng)絡(luò)實(shí)用技術(shù)速成
- 中小型局域網(wǎng)組建、管理與維護(hù)實(shí)戰(zhàn)
- Wireshark網(wǎng)絡(luò)分析就這么簡(jiǎn)單
- 網(wǎng)管工具使用與技巧大全
- 夢(mèng)工廠之材質(zhì)N次方:Maya材質(zhì)手冊(cè)
- AIoT應(yīng)用開發(fā)與實(shí)踐
- 無線傳感器網(wǎng)絡(luò)定位技術(shù)
- 局域網(wǎng)組成實(shí)踐
- 5G時(shí)代的大數(shù)據(jù)技術(shù)架構(gòu)和關(guān)鍵技術(shù)詳解
- Web用戶查詢?nèi)罩就诰蚺c應(yīng)用