React组件的生命周期
1. 引出生命周期
<script type="text/babel">
//生命周期回调函数===生命周期钩子函数====生命周期函数====生命周期钩子
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)
}
//组件将要卸载
componentWillUnmount(){
//清除定时器
clearInterval(this.timer)
}
// render调用的时机:初始化渲染,状态更新之后
render(){
return (
<div>
<h2 style={{opacity:this.state.opacity}}>好好学习react</h2>
<button onClick={this.death}>加油!</button>
</div>
)
}
}
ReactDOM.render(<Life/>,document.getElementById("test"))
</script>