javascript、react——setInterval方法,react的componentDidMount生命週期方法
阿新 • • 發佈:2021-02-13
技術標籤:# javascript# reactreactjavascript
1.程式碼
<body>
<div id="test"></div>
<script type="text/babel">
"use strict";
class Life extends React.Component {
state = { opacity: 1 };
death = () => {
clearInterval (this.timer);
ReactDOM.unmountComponentAtNode(document.getElementById("test"));
};
componentDidMount() {
this.timer = setInterval(() => {
let { opacity } = this.state;
opacity -= 0.1;
if (opacity <= 0) opacity = 1 ;
this.setState({ opacity });
}, 200);
}
render() {
console.log("render");
return (
<div>
<h2 style={{ opacity: this.state.opacity }}>欄位</h2>
<button onClick={this.death}> 解除安裝該元件</button>
</div>
);
}
}
ReactDOM.render(<Life />, document.getElementById("test"));
</script>
</body>
2.程式碼講解
- serInterval方法有兩個引數,第一個引數是一個方法,第二個引數是一個毫秒值。serInterval方法的作用是重複執行第一個引數方法,間隔第二個引數的毫秒時間。
- componentDidMount方法是當render執行後,自動執行的一個生命週期方法
- serInterval使用後需要記得清除它,clearInterval(this.timer);該方法用於清除定時器,引數為要清除的目標定時器