一、效果图
定时器启动(文本显示/隐藏)...
清除定时器...
二、代码实现
Time.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom'
class Time extends Component {
constructor(props) {
super(props);
this.state = {
opacity: 1
}
}
componentDidMount() {
// 启动循环定时器
this.intervalId = setInterval(function () {
console.log("定时器启动...")
let {opacity} = this.state
opacity -= 0.1
if (opacity <= 0) {
opacity = 1
}
// 更新状态
this.setState({opacity})
}.bind(this), 200)
}
componentWillUnmount() {
// 清除定时器
clearInterval(this.intervalId)
}
destroyLife() {
ReactDOM.unmountComponentAtNode(document.getElementById("root"))
}
render() {
const {opacity} = this.state
return (
<div>
<h2 style={{opacity}}>{this.props.msg}</h2><br/>
<button onClick={this.destroyLife}>结束定时器</button>
</div>
);
}
}
export default Time;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Time from "./components/Time";
// 2. 渲染组件标签
ReactDOM.render(<Time msg="React太难了"/>,
document.getElementById('root')
);