官术网_书友最值得收藏!

  • 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:

  1. 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
  1. 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 falsewe 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

  1. If you run the application, you will see this view:
  1. 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:

主站蜘蛛池模板: 德令哈市| 娄烦县| 香格里拉县| 津市市| 信宜市| 仪征市| 东方市| 苍梧县| 大港区| 上思县| 新蔡县| 佛学| 浦城县| 开封市| 呼图壁县| 疏勒县| 彰化县| 双柏县| 洛阳市| 贵州省| 绥棱县| 六安市| 金阳县| 三原县| 岳普湖县| 乐至县| 阿拉善右旗| 侯马市| 梁山县| 泗阳县| 广丰县| 新和县| 青海省| 怀远县| 乌拉特中旗| 蓝田县| 化隆| 天峨县| 大足县| 曲阳县| 木兰县|