个人 尚硅谷React全家桶学习笔记(13)

个人 尚硅谷React全家桶学习笔记(十三)

37.引出生命周期

class Life extends React.Component{
		state={
			opacity:1
		}
		death=()=>{
			//卸载组件
			ReactDOM.unmountComponentAtNode(document.getElementById('test'))
		}
		//组件挂载完毕后调用 并且只调用一次
		componentDidMount(){
			this.timer=setInterval(() => {
				//获取原状态
				let{opacity}=this.state
				//减小0.1
				opacity-=0.1
				if(opacity<=0) opacity=1
				//设置新的透明度
				this.setState({opacity})
			},200);
		}
		//组件将要卸载时调用一次
		componentWillUnmount(){
				//清除定时器
				clearInterval(this.timer)
		}
		

	render(){
	
		return(

		<div>
			<h2 style={
  {opacity:this.state.opacity}}>React学不会怎么办?</h2>
			<button onClick={this.death}>不活了</button>
		</div>

		)
	}
}
ReactDOM.render(<Life/>,document.getElementById('test'))

在合适的时机 调用函数

例如 componentDidMount() 是在函数挂载完毕后调用且只调用一次的函数

componentWillUnmount() 是在组件卸载前调用且只调用一次的函数

1.组件从创建到死亡会经历一些特定的阶段。

2.React组件中包含一系列勾子函数(生命周期回调函数),会在特定时刻调用。

3.我们在定义组件时,会在特定的生命周期回调函数中做特定的工作。

38.生命周期(旧)_组件挂载流程

class Count extends React.Component{
	//构造器
	constructor(props){
		console.log('Count-constructor');
		super(props)
	}
	//组件将要挂载的钩子
	componentWillMount(){
		console.log('
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值