(demo)react类组件的生命周期

53 阅读1分钟

需求:定义组件实现以下功能:

1.让指定的文本做显示/隐藏的渐变动画

2.从完全可见,到彻底消失,耗时2S

3.点击“不活了”按钮从界面中卸载组件

component    生命周期.gif

class Life extends React.Component{
    //初始值
    state = {opacity:1}

    death = ()=>{
        // clearInterval(this.timer) 在这里清除定时器也可以

        //卸载组件
        ReactDOM.unmountComponentAtNode(document.getElementById('test'))
    }

    //组件挂载完就调用 (即只在初始化渲染完时调用一次)
    componentDidMount(){
        console.log('componentDidMount');

        //类里面不能随便写代码(只能写比如构造器、一些自定义的方法、赋值语句之类的),所以写在生命周期函数中
        //this指向组件实例,挂一个id为timer的定时器
        this.timer = setInterval(() => {
                //获取原状态
                let {opacity} = this.state
                //减小0.1
                opacity -= 0.1
                if(opacity <= 0) opacity = 1

                //设置新的透明度
                // {opacity:opacity} 对象里的key和保存值的变量名同名时,可以简写
                this.setState({opacity})
        }, 200);
    }

    //组件将要卸载(卸载组件前,写一些收尾工作)
    componentWillUnmount(){
        //清除定时器
        clearInterval(this.timer)
    }

    //render调用的时机:1、初始化渲染、2、状态更新之后
    render(){
        console.log('render');
        return(
            <div>
                <h2 style={{opacity:this.state.opacity}}>React学不会怎么办?</h2>
                <button onClick={this.death}>不活了</button>
            </div>
        )
    }
}

//渲染组件
ReactDOM.render(<Life/>,document.getElementById('test'))
/*
    render也是生命周期函数,所以这些componentDidMount函数是跟render同级别,
    也是由组件实例对象调用的(其中的this也是指向组件实例,所以不用把这些生命周期函数写成赋值语句+箭头函数的形式)
*/